12

Am making an hybrid mobile app and i need to store some of the data like for example if its a game : the high score etc .. so far am able to read data from JSON file using jquery .., but is it possible to write to JSON file ??!

Or is there any other way to do so ?

IDE - Eclipse ( plugin - IBM worklight studio )

Only HTML 5 and JS and JQ can be used !

Thanks (:

Dhayalan Pro
  • 579
  • 1
  • 5
  • 20

2 Answers2

16

You can write JSON into local storage and just use JSON.stringify (non-jQuery) to serialize a JavaScript object. You cannot write to any file using JavaScript alone. Just cookies or local (or session) storage.

var obj = {
    name: 'Dhayalan',
    score: 100
};

localStorage.setItem('gameStorage', JSON.stringify(obj));

And to retrieve the object later, such as on page refresh or browser close/open...

var obj = JSON.parse(localStorage.getItem('gameStorage'));
Jesse
  • 608
  • 8
  • 19
  • Thanks Works like charm :) but is there a limitation on the size of the file we can store in local storage ? – Dhayalan Pro Dec 29 '13 at 09:23
  • I'm glad it's working for you. See [here](http://stackoverflow.com/questions/2989284/what-is-the-max-size-of-localstorage-values) regarding size limitations. – Jesse Dec 29 '13 at 16:34
3

Dhayalan,

Your question is a little unclear to me, but let me take a stab at it. You can use JSON.stringify to turn a js object into a string, and you can store that string in localStorage provided that you're using HTML5. If it were me, I'd add some defensive checks around this, but you'll get the idea...

var dataObj = {};

dataObj.highScore = 100000;
dataObj.playerName = "Some Player";
localStorage.setItem("myKey", JSON.stringify(dataObj));
JohnC
  • 61
  • 4