简体   繁体   中英

Processing response in KRL

I'm sending a request to google via their API using KRL and this is the literal response I am getting back from them:

handleResponse({ "data": { "responses": [ { "response": "successful" } ] } } );

How do you recommend I process this via pick as it is not 'valid' JSON syntax? It contains valid JSON syntax, but as a whole is not valid. Thanks for your help.

Update: After looking at the Google translate API it looks like the JSONP callback parameter is optional. Don't specify a callback and you will no longer have this issue. : )

http://code.google.com/apis/language/translate/v2/using_rest.html#WorkingResults

Better option:

If you can, specify in your call to the google API that there be no callback function. If you can just request plain JSON instead of JSONP you can just use the pick operator.

Not so better option:

If the API only returns JSONP then you can do a regex replace to remove the padding from the JSON which will then allow you to use the pick operator.

What you'll need:

Full app example:

ruleset a60x494 {
  meta {
    name "jsonp-to-json-test"
    description <<
      jsonp-to-json-test
    >>
    author "Mike Grace"
    logging on
  }

  global {
    returnedJsonpAsString = 'handleResponse({ "data": { "responses": [ { "response": "successful" } ] } } );';
    datasource googleApi <- "blah blah blah";
  }

  rule fix_jsonp_to_json {
    select when pageview ".*"
    pre {
      cleanJson = returnedJsonpAsString.replace(re/^.*\((.*)\);/,"$1");
      response = cleanJson.decode().pick("$..response");
    }
    {
      notify("Response",response) with sticky = true;
      emit <|
        console.log(returnedJsonp);
        console.log(cleanJson);
      |>;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM