Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON+Javascript/jQuery. How to import data from a json file and parse it?

Tags:

If I have a JSON file named names.json with:

{"employees":[     {"firstName":"Anna","lastName":"Meyers"},     {"firstName":"Betty","lastName":"Layers"},     {"firstName":"Carl","lastName":"Louis"}, ]} 

How can I use its content in javascript?

like image 232
GarouDan Avatar asked May 07 '12 23:05

GarouDan


People also ask

How jQuery read data from JSON file?

Projects In JavaScript & JQuery To load JSON data using jQuery, use the getJSON() and ajax() method. The jQuery. getJSON( ) method loads JSON data from the server using a GET HTTP request. data − This optional parameter represents key/value pairs that will be sent to the server.

How read data from JSON file and convert it to a JavaScript object?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON. parse('{"name":"John", "age":30, "city":"New York"}');

How do I parse a JSON file?

If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.


2 Answers

An example how to do this could be:

<html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script type="text/javascript">     $(function(){         $.getJSON('names.json',function(data){             console.log('success');             $.each(data.employees,function(i,emp){                 $('ul').append('<li>'+emp.firstName+' '+emp.lastName+'</li>');             });         }).error(function(){             console.log('error');         });     }); </script> </head> <body>     <ul></ul> </body> </html> 
like image 82
kbec Avatar answered Oct 19 '22 05:10

kbec


You can simply include a Javascript file in your HTML that declares your JSON object as a variable. Then you can access your JSON data from your global Javascript scope using data.employees, for example.

index.html:

<html> <head> </head> <body>   <script src="data.js"></script> </body> </html> 

data.js:

var data = {   "employees": [{     "firstName": "Anna",     "lastName": "Meyers"   }, {     "firstName": "Betty",     "lastName": "Layers"   }, {     "firstName": "Carl",     "lastName": "Louis"   }] } 
like image 23
senornestor Avatar answered Oct 19 '22 05:10

senornestor