我想从一个外部文件中JSON对象,但我总是得到错误:格式不正确的,这点我的JSON文件的第一个 {
。我测试了这个网站我的JSON文件: http://jsonlint.com/ ,它是有效的。
这是我的JSON code:
{
员工:[{
名字:约翰,
姓氏:李四
},{
名字:安娜,
姓氏:史密斯夫妇
},{
名字:彼得,
姓氏:琼斯
}
]
}
这是我的脚本:
$。的getJSON(employe.json功能(数据){
文件撰写(data.employees [0] .firstName);
});
我是什么做错了吗?
解决方案 <脚本>
$(文件)。就绪(函数(){
$ .getJSON(employe.json功能(数据){
文件撰写(data.employees [0] .firstName);
});
});
< / SCRIPT>
或者代替文件写入
警报(data.employees [0] .firstName);
可能你会想$。每次迭代
<脚本>
$(文件)。就绪(函数(){
$ .getJSON(employe.json功能(数据){
$每个(data.employees,功能(的ArrayID,员工){
警报(employee.firstName);
});
});
});
< / SCRIPT>
I am trying to get a JSON object from an external file, but I always get the error: malformed , that points to the first {
of my JSON file. I tested my JSON file on this website: http://jsonlint.com/ and it is valid.
This is my JSON code:
{
"employees": [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"lastName": "Smith"
}, {
"firstName": "Peter",
"lastName": "Jones"
}
]
}
And this is my script:
$.getJSON("employe.json", function (data) {
document.write(data.employees[0].firstName);
});
What am I doing wrong?
解决方案<script>
$(document).ready(function() {
$.getJSON("employe.json", function(data) {
document.write(data.employees[0].firstName);
});
});
</script>
Or instead of document write
alert( data.employees[0].firstName);
Odds are you are going to want $.each iteration
<script>
$(document).ready(function() {
$.getJSON("employe.json", function(data) {
$.each(data.employees, function(arrayID, employee) {
alert(employee.firstName);
});
});
});
</script>