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

2020-05-17 08:24发布

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?

7条回答
可以哭但决不认输i
2楼-- · 2020-05-17 08:56

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>`
查看更多
男人必须洒脱
3楼-- · 2020-05-17 09:00

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楼-- · 2020-05-17 09:04

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);
})
查看更多
祖国的老花朵
5楼-- · 2020-05-17 09:05

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楼-- · 2020-05-17 09:09

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/

查看更多
\"骚年 ilove
7楼-- · 2020-05-17 09:10

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>
查看更多
登录 后发表回答