JSON+Javascript/jQuery. How to import data from a

2020-05-17 08:14发布

问题:

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:

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>


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


回答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/



回答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/



回答5:

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


回答6:

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>`


回答7:

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