Apoorv
Apoorv

Reputation: 2043

How to parse The following JSON in Javascript?

I am making a web app for nokia S40 platform . I am calling a web service using Javascript that returns the Following JSON

{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http:\/\/bit.ly\/msapps", "long_url": "http:\/\/www.microsoft.com\/web\/gallery\/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } } 

I want to obtain the "short_url" and "long_url " values

I am using eval as var obj = eval ("(" + xmlhttp.responseText + ")");

where xmlhttp.responseText conatains the JSON response. Please help

Upvotes: 1

Views: 164

Answers (3)

Vinod Louis
Vinod Louis

Reputation: 4876

tried this and worked

 var s = '{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http://bit.ly/msapps", "long_url": "http://www.microsoft.com/web/gallery/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } } '

 var d = JSON.parse(s);
 console.log(d.data.expand[0].short_url);
 console.log(d.data.expand[0].long_url);

Upvotes: 9

Hersh
Hersh

Reputation: 640

This expression

JSON.parse('{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http:\/\/bit.ly\/msapps", "long_url": "http:\/\/www.microsoft.com\/web\/gallery\/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } }').data.expand[0].short_url

returns "http://bit.ly/msapps"

Upvotes: 1

Exception
Exception

Reputation: 8379

How about this

var json = "{}" // Your JSON string
json = new Function('return ' + json)();
console.log(json.data.expand[0].short_url, json.data.expand[0].long_url);

Upvotes: -3

Related Questions