0

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\"]]"}
Jonathan Naguin
  • 14,526
  • 6
  • 46
  • 75
Shailesh
  • 492
  • 3
  • 9
  • 27

5 Answers5

3

"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.

ddavison
  • 28,221
  • 15
  • 85
  • 110
1

Try :

var myObject = JSON.parse(your_JSON_variable);
Pouki
  • 1,654
  • 12
  • 18
1

Read:

var obj=JSON.parse(jsonstring);

obj.getTemperatureResult// contains the city array

back to string

JSON.stringify(obj);
cocco
  • 16,442
  • 7
  • 62
  • 77
1

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.

jterry
  • 6,209
  • 2
  • 30
  • 36
  • [Reference on browser support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FJSON#Browser_compatibility) for `JSON`. – jterry Jul 09 '13 at 12:48
  • yeah .. jquery is slow.jQuery is a polyfill for older browsers and just slows down everything. – cocco Jul 09 '13 at 12:50
0

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);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375