Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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?

share|improve this question
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. – GarouDan May 14 '12 at 0:06
up vote 4 down vote accepted

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>
share|improve this answer

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/

share|improve this answer
    
oh. yes. now works^^. Thx so much. I was thing the problem is in jquery code. – GarouDan May 7 '12 at 23:45
    
+1 The invalid JSON went right over my head. – cliffs of insanity May 7 '12 at 23:46

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/

share|improve this answer
    
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 May 7 '12 at 23:37
    
@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? – cliffs of insanity May 7 '12 at 23:40

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"
  }]
}
share|improve this answer
    
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 . – Prerna Jain Jun 10 at 4:50

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);
?>
share|improve this answer
    
The file already contains json, why json_encode what's already json? He could just get names.json directly without the last php wrapper. – ccKep May 7 '12 at 23:38
    
Interesting solution xbonez. I will try a little using jQuery e javascript, but probably this solve my problem too. – GarouDan May 7 '12 at 23:38
    
thx xbonez, I will keep in mind this solution too. – GarouDan May 7 '12 at 23:45
    
And for what you are parsing fully-js object names to json obj. This not make sense like encoding json to... double json – kbec May 8 '12 at 1:54
    
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. – xbonez May 8 '12 at 2:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.