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

67,240

Solution 1

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>

Solution 2

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"
  }]
}

Solution 3

Your JSON file does not contain valid JSON. Try the following instead.

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

You should then see a response. Check out http://jsonlint.com/

Solution 4

In the jQuery code, you should have the employees property.

data.employees[0].firstName

So it would be like this.

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
    $.getJSON("names.json", function(data) {
        console.log(data);
        $('body').append(data.employees[0].firstName);
    });
</script>
</body>
</html>

Of course you'll need that property for the non jQuery version too, but you'd need to parse the JSON response first.

Also keep in mind that document.write is destroying your entire page.


If you're still having trouble, try the full $.ajax request instead of the $.getJSON wrapper.

    $.ajax({
        url: "names.json",
        dataType: "json",
        success: function(data) {
            console.log(data);
            $('body').append(data.employees[0].firstName);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log('ERROR', textStatus, errorThrown);
        }
    });

http://api.jquery.com/jquery.ajax/

Solution 5

For those sent here by Google after the fall of JQuery, use Fetch API

fetch("test.json").then(async (resp) => {
  const asObject = await resp.json();
  console.log(asObject);
})
Share:
67,240
GarouDan
Author by

GarouDan

Senior Full-Stack Software Engineer specialized in backend. 8+ years of commercial experience. Very interested in AI and ML. Bachelor’s degree in Information Systems, post-graduation's degree in Java Technology and Development for Mobile Devices. Knowledge in several programming languages (mainly Kotlin and Java), technologies and other topics related to IT and mathematics. Self-teaching, ease in learning new technologies or improving and optimizing processes, ability in computer and exact sciences, teamwork. Bachelor's thesis defended in the field of AI and Fuzzy Systems. My CV is available at this link.

Updated on July 09, 2022

Comments

  • GarouDan
    GarouDan almost 2 years

    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?

    • GarouDan
      GarouDan almost 12 years
      I had changed the question and fixed the errors. Now I think it could receive upvotes and would be a good reference to other people.
  • GarouDan
    GarouDan about 12 years
    hi cliffs, still not working to me. Can you post the entire code? The script was in head, but now is in the body and didn't work. =/
  • ccKep
    ccKep about 12 years
    The file already contains json, why json_encode what's already json? He could just get names.json directly without the last php wrapper.
  • GarouDan
    GarouDan about 12 years
    Interesting solution xbonez. I will try a little using jQuery e javascript, but probably this solve my problem too.
  • cliffs of insanity
    cliffs of insanity about 12 years
    @GarouDan: Not sure what you mean when you say it doesn't work. Is the callback invoked at all? Are you getting any errors in the console?
  • GarouDan
    GarouDan about 12 years
    oh. yes. now works^^. Thx so much. I was thing the problem is in jquery code.
  • kbec
    kbec about 12 years
    And for what you are parsing fully-js object names to json obj. This not make sense like encoding json to... double json
  • Ayush
    Ayush about 12 years
    Because when php reads it in using file_get_contents, it reads it in as a string. The string needs to be parsed to be available as a javascript object.
  • Prerna Jain
    Prerna Jain almost 8 years
    You need to add this statement to file data.js : """" module.exports = data; """" Otherwise you will not be able to import data variable value in any other file through data.js .