Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing response in KRL

Tags:

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.

like image 672
jshakespear Avatar asked Jun 17 '26 16:06

jshakespear


1 Answers

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:

  • Convert returned JSONP into a string using beesting or encode function
  • Replace function
  • Decode function
  • Pick operator

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);
      |>;
    }
  }
}
like image 189
Mike Grace Avatar answered Jun 21 '26 18:06

Mike Grace



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!