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

22

如果我有一个名为 names.jsonJSON 文件,其中包含:

{"employees":[
    {"firstName":"Anna","lastName":"Meyers"},
    {"firstName":"Betty","lastName":"Layers"},
    {"firstName":"Carl","lastName":"Louis"},
]}

我该如何在JavaScript中使用它的内容?


2
我已经修改了问题并修复了错误。现在我认为它可以得到赞同,并且对其他人来说是一个很好的参考。 - GarouDan
7个回答

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>

9
你可以在HTML中包含一个JavaScript文件,将你的JSON对象声明为一个变量。然后你可以通过全局JavaScript作用域来访问你的JSON数据,例如使用data.employees

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

你需要将以下语句添加到 data.js 文件中:"""" module.exports = data; """"否则,你将无法通过 data.js 在任何其他文件中导入 data 变量的值。 - Prerna Jain

6
您的JSON文件不包含有效的JSON。请尝试以下方法。
 {
     "employees": 
     [
         {
             "firstName": "Anna",
             "lastName": "Meyers"
         },
         {
             "firstName": "Betty",
             "lastName": "Layers"
         },
         {
             "firstName": "Carl",
             "lastName": "Louis"
         }
     ]
 }

接着您应该能看到响应结果。请点击http://jsonlint.com/查看。


哦,是的。现在可以工作了^^。非常感谢。我一直以为问题出在 jQuery 代码上。 - GarouDan
具体来说,问题出在员工区域的尾随逗号上。JSON不支持尾随逗号。 - Michael Mior

5
在jQuery代码中,你应该有employees属性。
data.employees[0].firstName

那么,它将会像这样。
<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>

当然,即使是非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);
        }
    });

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


嗨,克利夫斯,对我来说还是不起作用。你能发布整个代码吗?脚本在头部时可以工作,但现在在正文中却无法工作。 = / - GarouDan
@GarouDan:不确定你说它不起作用是什么意思。回调函数是否被调用?控制台中是否有任何错误? - cliffs of insanity

1

我知道答案早已给出,但这个结果在谷歌上排名第一。

然而,我不想使用jquery,在原生JS中,我发现这个快速教程比senornestor的回答更简洁(它还允许根据变量加载文件):

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

在你的HTML文件中:
`<script src="myscript.js"></script>`

1

如果不使用jQuery,您可以使用Fetch API。截至2023年1月,它被大约96%的浏览器支持。

fetch("test.json").then(async (resp) => {
  const asObject = await resp.json();
  console.log(asObject);
})

0
如果你想使用PHP。
<?php
    $contents = file_get_contents('names.json');
?>
<script>
    var names = <?php echo $contents; ?>
    var obj = JSON.parse(names);

    //use obj
</script>

可以选择异步使用:

<script>
    $(document).ready(function(){
        $.get("get_json.php?file=names",function(obj){
            //use obj here          
        },'json');
    });
</script>

PHP编程语言:

<?php
    $filename = $_GET['file'] . '.json';
    $data['contents'] = file_get_contents($filename);
    echo json_encode($data);
?>

文件已经包含了json,为什么还要对已经是json的内容进行json_encode呢?他可以直接获取names.json,而不需要使用最后的php包装器。 - ccKep
很有趣的解决方案xbonez。我会尝试使用jQuery和JavaScript,但这可能也能解决我的问题。 - GarouDan
你正在将完整的 JS 对象“names”解析为 JSON “obj”。这样做就好像将JSON编码成双重JSON,没有意义。 - kbec
因为当 PHP 使用 file_get_contents 读取时,它会将其作为字符串读入。该字符串需要被解析才能作为 JavaScript 对象可用。 - Ayush

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接