I have a json response which has a function call inside. It looks like string after parsing
"foo({a: 5}, 5, 100)"
How can I extract the first argument of the function call (in this case it’s {a: 5})?.
update
Here is the code from the server side
var request = require('request')
, cheerio = require('cheerio');
var url = 'http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q=test&sl=en&tl=en';
request({url: url, 'json': true}, function(error, resp, body){
console.log(typeof JSON.parse(body)); // => string
});
The Google Dictionary API (undocumented) uses JSONP, which is not really JSON, so you can’t use it in your node.js (as you noted in your comment) in the way that you’d like. You’ll have to
eval()the response.Notice how the query params has
callback=dict_api.callbacks.id100? That means that the returned data is going to be returned like this:dict_api.callbacks.id100(/* json here */, 200, null)So, you have two options: 1: create a function in your code:
Alternatively, you can pull off the start (
dict_api.callbacks.id100() and end (,200,null)[assuming this will always be the same]), and thenJSON.parse()the resulting string.