Shailesh
Shailesh

Reputation: 492

How to Read Json String

I am NEW IN json ,How can i read given JSON string in JavaScript.I want Pass associated array in High Chart .

{"getTemperatureResult":"[[\"{name: 'Tokyo',data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]}\",\"{name: 'New York',data: [-0.2, 0.8, 5.7, 11.3, 17.0, 22.0, 24.8, 24.1, 20.1, 14.1, 8.6, 2.5]}\",\"{name: 'Berlin',data: [-0.9, 0.6, 3.5, 8.4, 13.5, 17.0, 18.6, 17.9, 14.3, 9.0, 3.9, 1.0]}\",\"{name: 'London',data: [3.9, 4.2, 5.7, 8.5, 11.9, 15.2, 17.0, 16.6, 14.2, 10.3, 6.6, 4.8]}\"],[\"Jan\",\"Feb\",\"Mar\",\"Apr\",\"May\",\"Jun\",\"July\",\"Aug\",\"Sep\",\"Oct\",\"Nov\",\"Dec\"]]"}

Upvotes: 0

Views: 2353

Answers (5)

ddavison
ddavison

Reputation: 29102

"How can I read given JSON String in JavaScript".

The verb "read" is a bit ambiguous, but if you wanted to evaluate it, you can use

JSON.parse()

You need to encapsulate the JSON in a quote that isn't used within your JSON to actually parse it, but looking at your code, there is no easy way to do it.. My advice to you is -

That JSON at some point is returned from some service as a string. Do a global replace on all single quotes, to replace them with a \" because as it stands, there is no way to evaluate it with single or double quotes.

A little tip on JSON too - be sure to run JSON through a json lint to make sure that it is valid.. trouble can stem from not having properly formatted JSON.

Use http://jsonlint.com for validating it.

Upvotes: 3

Bergi
Bergi

Reputation: 665574

Your JSON is odd. Inside the object you've nested another JSON string - instead of the array directly which it presents.

// Assuming your got the string from a XHR response directly:
var obj = JSON.parse(response);
// or you've got the object directly embedded in your script:
var obj = {"getTemperatureResult":"[[…]]"};

// then do:
var arr = JSON.parse(obj.getTemperatureResult);

Upvotes: 0

jterry
jterry

Reputation: 6269

You can't always count on the browser having JSON functions available out-of-the-box.

I'd suggest either using jQuery's $.parseJSON function or tapping into the excellent json2 solution.

Upvotes: 1

cocco
cocco

Reputation: 16716

Read:

var obj=JSON.parse(jsonstring);

obj.getTemperatureResult// contains the city array

back to string

JSON.stringify(obj);

Upvotes: 1

Pouki
Pouki

Reputation: 1664

Try :

var myObject = JSON.parse(your_JSON_variable);

Upvotes: 1

Related Questions