1

Given JSON containing:

[
{"myKey":"A","status":0,"score":1.5},{"myKey":"C","status":1,"score":2},
{"myKey":"D","status":0,"score":0.2},{"myKey":"E","status":1,"score":16},
{"myKey":"F","status":0,"score":0.4},{"myKey":"G","status":1,"score":3}
]

Given JS such:

MyJSON = $.getJSON('http://d.codio.com/hugolpz/getJson--/App/data/statusStarter2.json' );

How to get the JSON's content (stringified) into localStorage.data ?

Note: localStorage.data = JSON.stringify(MyJSON); returns {"readyState":1}, which is not my wish. I looked into jQuery.getJSON/, but I'am quite confused by the function (data).

Hugolpz
  • 17,296
  • 26
  • 100
  • 187
  • the `function(data)` is an anonymous callback function that gets called when the json has been retrieved, and will contain your data in the variable `data` or whatever you call the parameter. – Patrick Evans Jun 30 '13 at 14:30

2 Answers2

3

getJSON works asynchronously and what it returns is AJAX request object. So use success callback function of getJSON to recieve the data

$.getJSON('http://d.codio.com/hugolpz/getJson--/App/data/statusStarter2.json', function(data) {
  // do JSON.stringify(data) here
});
Diode
  • 24,570
  • 8
  • 40
  • 51
2

Did you try :

localStorage.setItem('data', JSON.stringify(MyJSON));

and

var JSON = localStorage.getItem('data');

and as ajax is async :

$.getJSON('url', function(MyJSON) {
     localStorage.setItem('data', JSON.stringify(MyJSON));
});
adeneo
  • 312,895
  • 29
  • 395
  • 388