Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 localStorage (XML/JSON data)

I have an XML file as shown below:

<itemnumbers>
<item>
<itemno>123</itemno>
<desc>Desc about 123</desc>
</item>

<item>
<itemno>456</itemno>
<desc/>
</item>

...

</itemnumbers>

I would like to use the HTML5 localStorage to store the data (and retrieve for quicker access) since the XML data does not change regularly.

I am planning to convert it into JSON first and then store it in the localStorage. Should I do that in the code or have the data upfront in the .JSON file instead of the .xml file?

How do I parse the data later? Currently I am using jQuery code to parse...something like:

$(this).find("itemno").each(function()
{
$(this).text();
$(this).next().text()
}

Would the above code work after the JSON conversion?

I would like suggestions on the best way to approach this.

like image 873
copenndthagen Avatar asked Nov 27 '11 07:11

copenndthagen


1 Answers

I agree with some of the comments that you could just continue using XML. If you want to convert to JSON, you would use a For In loop in javascript to loop through it just as you would an object in javascript.

Your data in JSON:

{"itemnumbers": 
    { "item": {"itemno": 123, "desc": "Desc about 123"} }
    { "item": {"itemno": 456, "desc": "Desc about 456"} }
}

Looping through your data where data is the JSON object above:

for (item in data.itemnumbers) {
    //do something with item data
    console.log(data.itemnumbers[item].itemno);
    console.log(data.itemnumbers[item].desc);
}

To save an object in localStorage you must transform it to a string format that you can fetch back out again as an object. You can use JSON.stringify() to make an object a string and JSON.parse() to pull it back out:

//saving object to localStorage
localStorage['my_data'] = JSON.stringify(data);

//fetching object from localStorage
data = JSON.parse(localStorage['my_data']);

Beware because these methods aren't supported on IE7 and below so you'll need to find a parsing library compatible with them. Here's a post that might help with compatibility:

Safely turning a JSON string into an object

like image 173
Ben L Avatar answered Oct 04 '22 03:10

Ben L