Processing response in KRL
I'm sending a request to google via their API using KRL and this is the literal response I am gettin开发者_高级运维g 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:
- 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);
|>;
}
}
}
精彩评论