JSON +的Javascript/jQuery的.如何从json文件导入数据并解析它?

Gar*_*Dan 20 javascript jquery json getjson

如果我有一个JSON名为names.json的文件:

{"employees":[
    {"firstName":"Anna","lastName":"Meyers"},
    {"firstName":"Betty","lastName":"Layers"},
    {"firstName":"Carl","lastName":"Louis"},
]}
Run Code Online (Sandbox Code Playgroud)

如何在javascript中使用其内容?

kbe*_*bec 12

如何执行此操作的示例可以是:

<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>
Run Code Online (Sandbox Code Playgroud)


sen*_*tor 7

您只需在HTML中包含一个Javascript文件,即将JSON对象声明为变量.然后,您可以使用data.employees例如全局Javascript范围访问JSON数据.

index.html的:

<html>
<head>
</head>
<body>
  <script src="data.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

data.js:

var data = {
  "employees": [{
    "firstName": "Anna",
    "lastName": "Meyers"
  }, {
    "firstName": "Betty",
    "lastName": "Layers"
  }, {
    "firstName": "Carl",
    "lastName": "Louis"
  }]
}
Run Code Online (Sandbox Code Playgroud)


rpo*_*sky 6

您的JSON文件不包含有效的JSON.请尝试以下方法.

 {
     "employees": 
     [
         {
             "firstName": "Anna",
             "lastName": "Meyers"
         },
         {
             "firstName": "Betty",
             "lastName": "Layers"
         },
         {
             "firstName": "Carl",
             "lastName": "Louis"
         }
     ]
 }
Run Code Online (Sandbox Code Playgroud)

然后你应该看到一个回复​​.查看http://jsonlint.com/


cli*_*ity 5

在jQuery代码中,您应该拥有该employees属性.

data.employees[0].firstName
Run Code Online (Sandbox Code Playgroud)

所以就是这样.

<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>
Run Code Online (Sandbox Code Playgroud)

当然,你也需要非jQuery版本的属性,但是你需要先解析JSON响应.

另请注意,这document.write会破坏整个页面.


如果您仍然遇到问题,请尝试完整$.ajax请求而不是$.getJSON包装器.

    $.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);
        }
    });
Run Code Online (Sandbox Code Playgroud)

http://api.jquery.com/jquery.ajax/