Parsing a local JSON file using jQuery and Javascript

I am trying to parse a JSON file located on my computer. I want to make it out. The JSON file has the following structure:

{ "sites": { "site": [ { "id": "01", "name": "Sito 1", "src": "localhost/root/coupon/sito1", "expiryDate": "29 Ago 2013" }, { "id": "02", "name": "Sito 2", "src": "localhost/root/coupon/sito2", "expiryDate": "30 Ago 2013" }, { "id": "Sito 3", "name": "Sito 3", "src": "localhost/root/coupon/sito2", "expiryDate": "31 Ago 2013" } ] } } 

In my html, I import the jQuery library, and I created a function that will load when the page loads. Code below:

 <!DOCTYPE html> <html lang="it"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/> <title>Lista coupon</title> <script type="text/javascript" src="jquery-1.9.1.min.js"></script> <script type="text/javascript" charset="utf-8"> function loadJson() { window.alert("Carico il contenuto del file JSON per popolare la lista"); $(document).ready(function() { $.getJSON('data.json', function(json) { console.log(json); }); }); } </script> </head> <body onload="loadJson();"> <div id="header"> <h1>Lista coupon salvati</h1> </div> <div id="content"> <p>Di seguito trovi tutte le promozioni salvate</p> </div> <div id="footer"> </div> </body> </html> 

Now I saw on the firebug console that it can read the JSON file correctly, but I don’t know how to parse this JSON. I searched on google, but I found many examples that use remote JSON. Can you help me understand how to parse a local JSON file? thank you

PS: pay attention to the site that I publish here for a mobile browser.

+6
source share
2 answers

getJSON it for you.

Just delete the line var obj = $.parseJSON(json); (since this will erase the object and try to parse it as JSON (which it will not)).

+8
source

I don't think you need to parse json. It will automatically parse json as you are using $ .getJSON ().

+2
source

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


All Articles