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
});
foo({a: 5}, 5, 100);
function foo(){
var the_bit_you_want = arguments[0];
console.log(the_bit_you_want);
}
It's quite simple, use the following in your foo-function:
arguments[0];
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:
var dict_api = { callbacks: { id100: function (json_data) {
console.log(json_data);
}};
request({url: url, 'json': true}, function(error, resp, body){
// this is actually really unsafe. I don't recommend it, but it'll get the job done
eval(body);
});
Alternatively, you can pull off the start (dict_api.callbacks.id100() and end (,200,null) [assuming this will always be the same]), and then JSON.parse() the resulting string.
request({url: url, 'json': true}, function(error, resp, body){
// this is actually really unsafe. I don't recommend it, but it'll get the job done
var json_string = body.replace('dict_api.callbacks.id100(', '').replace(',200,null)', '');
console.log(JSON.parse(json_string));
});