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?

1
  • 2
    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. Commented May 14, 2012 at 0:06

7 Answers 7

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>
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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 .
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/

2 Comments

oh. yes. now works^^. Thx so much. I was thing the problem is in jquery code.
Specifically, the problem was the trailing comma in the employees area. JSON does not support trailing commas.
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/

2 Comments

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. =/
@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?
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>`

Comments

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);
})

Comments

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);
?>

4 Comments

The file already contains json, why json_encode what's already json? He could just get names.json directly without the last php wrapper.
Interesting solution xbonez. I will try a little using jQuery e javascript, but probably this solve my problem too.
And for what you are parsing fully-js object names to json obj. This not make sense like encoding json to... double json
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.