JSON+Javascript/jQuery。如何从json文件导入数据并解析它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10490473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON+Javascript/jQuery. How to import data from a json file and parse it?
提问by GarouDan
If I have a JSON
file named names.jsonwith:
如果我有一个JSON
名为names.json的文件:
{"employees":[
{"firstName":"Anna","lastName":"Meyers"},
{"firstName":"Betty","lastName":"Layers"},
{"firstName":"Carl","lastName":"Louis"},
]}
How can I use its content in javascript?
我如何在 javascript 中使用它的内容?
采纳答案by kbec
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>
回答by senornestor
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.
您可以简单地在 HTML 中包含一个 Javascript 文件,该文件将您的 JSON 对象声明为变量。然后,您可以使用data.employees
例如从全局 Javascript 范围访问您的 JSON 数据。
index.html:
索引.html:
<html>
<head>
</head>
<body>
<script src="data.js"></script>
</body>
</html>
data.js:
数据.js:
var data = {
"employees": [{
"firstName": "Anna",
"lastName": "Meyers"
}, {
"firstName": "Betty",
"lastName": "Layers"
}, {
"firstName": "Carl",
"lastName": "Louis"
}]
}
回答by rposky
Your JSON file does not contain valid JSON. Try the following instead.
您的 JSON 文件不包含有效的 JSON。请尝试以下操作。
{
"employees":
[
{
"firstName": "Anna",
"lastName": "Meyers"
},
{
"firstName": "Betty",
"lastName": "Layers"
},
{
"firstName": "Carl",
"lastName": "Louis"
}
]
}
You should then see a response. Check out http://jsonlint.com/
然后您应该会看到响应。查看http://jsonlint.com/
回答by cliffs of insanity
In the jQuery code, you should have the employees
property.
在 jQuery 代码中,您应该拥有该employees
属性。
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.
当然,非 jQuery 版本也需要该属性,但您需要先解析 JSON 响应。
Also keep in mind that document.write
is destroying your entire page.
还要记住,这document.write
会破坏您的整个页面。
If you're still having trouble, try the full $.ajax
request instead of the $.getJSON
wrapper.
如果您仍然遇到问题,请尝试完整$.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);
}
});
回答by xbonez
If you want to use PHP.
如果你想使用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:
<?php
$filename = $_GET['file'] . '.json';
$data['contents'] = file_get_contents($filename);
echo json_encode($data);
?>
回答by Mael Abgrall
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 tutorialcleaner than senornestor answer (it also allow to load files depending on a variable) :
但是我不想使用 jquery,所以在 vanilla 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();
and on your html file:
并在您的 html 文件中:
`<script src="myscript.js"></script>`