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 HTML5 localStorage to store data (and retrieve it for faster access), because XML data does not change regularly.

I plan to convert it to JSON first, and then save it to localStorage. Should I do this in code or have data in a .JSON file instead of a .xml file?

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

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

Will the above code work after JSON conversion?

I would like you to suggest a better way to approach this.

+6
source share
2 answers

I agree with some comments that you can just keep using XML. If you want to convert to JSON, you must use the For In loop in javascript to scroll it in exactly the same way you would use an object in javascript.

Your data in JSON:

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

Looping around your data where the data is a 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 store an object in localStorage, you must convert it to a string format that you can return back as an object. You can use JSON.stringify () to make the object a string and JSON.parse () to pull it back:

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

Beware, because these methods are not supported in IE7 and below, so you need to find a compatible parsing library with them. Here's a post that might help with compatibility:

Safely turning a JSON string into an object

+1
source

I would suggest you write a script that converts the XML data to JSON, and then sends it to the client side and saves.

Then parse JSON when necessary, which is very easy to do. In the same way as: -

 var jsonObject = JSON.parse(yourObjectInJSON); 

Penetration through it: -

 for (item in jsonObject.itemnumbers) { //do something with item data } 
0
source

Source: https://habr.com/ru/post/902475/


All Articles