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

7

23

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?

Tapster answered 7/5, 2012 at 23:23 Comment(1)
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.Tapster
B
14

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>
Batwing answered 7/5, 2012 at 23:45 Comment(0)
S
9

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"
  }]
}
Scrawny answered 2/4, 2015 at 16:10 Comment(1)
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 .Brute
C
6

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/

Catanddog answered 7/5, 2012 at 23:43 Comment(2)
oh. yes. now works^^. Thx so much. I was thing the problem is in jquery code.Tapster
Specifically, the problem was the trailing comma in the employees area. JSON does not support trailing commas.Hypno
A
5

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/

Alameda answered 7/5, 2012 at 23:27 Comment(2)
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. =/Tapster
@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?Alameda
T
1

I know the answer was given a long time ago, but this result is showing in first position on google.

However I don't want to use jquery, so in vanilla JS , I found this quick tutorial cleaner than senornestor answer (it also allow to load files depending on a variable) :

function loadJSON(filelocation, callback) {   

  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', filelocation, true); // Replace 'my_data' with the path to your file
  xobj.onreadystatechange = function () {
    if (xobj.readyState == 4 && xobj.status == "200") {
      // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
      callback(xobj.responseText);
    }
  };
  xobj.send(null);  
}

function init() {
  var location = "myfile.json";
  loadJSON(filelocation=location,  function(response) {
    // Parse JSON string into object
    loadedJSON = JSON.parse(response);
    console.log(loadedJSON.somethingsomething);
  });
}

init();

and on your html file:

`<script src="myscript.js"></script>`
Turnspit answered 11/4, 2018 at 18:37 Comment(0)
B
1

To do this without jQuery, you can use the Fetch API. As of January 2023, it is supported by ~96% of browsers.

fetch("test.json").then(async (resp) => {
  const asObject = await resp.json();
  console.log(asObject);
})
Brusque answered 16/9, 2019 at 18:27 Comment(0)
F
0

If you want to use PHP.

<?php
    $contents = file_get_contents('names.json');
?>
<script>
    var names = <?php echo $contents; ?>
    var obj = JSON.parse(names);

    //use obj
</script>

Optionally, use it async:

<script>
    $(document).ready(function(){
        $.get("get_json.php?file=names",function(obj){
            //use obj here          
        },'json');
    });
</script>

The PHP:

<?php
    $filename = $_GET['file'] . '.json';
    $data['contents'] = file_get_contents($filename);
    echo json_encode($data);
?>
Ferren answered 7/5, 2012 at 23:27 Comment(4)
The file already contains json, why json_encode what's already json? He could just get names.json directly without the last php wrapper.Redhanded
Interesting solution xbonez. I will try a little using jQuery e javascript, but probably this solve my problem too.Tapster
And for what you are parsing fully-js object names to json obj. This not make sense like encoding json to... double jsonBatwing
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.Ferren

© 2022 - 2024 — McMap. All rights reserved.