所以我只想将1个值存储在同一文件夹中的外部JSON文件中。每次我尝试获取该项时,chrome都会显示“意外令牌:”,它会显示另一个错误,指出JSON.parse(data)方法中的数据是错误的。无论哪种方式,无论有没有parse(),我都会得到令牌错误。它不喜欢"e1" :
部分,json文件的该部分下面有一条红色错误行。我在这个网站和其他网站上看到了大约6条建议,但它对我的特定问题没有帮助。有什么想法吗?
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Objects 2</title>
<script type="text/javascript" src="data.json"></script>
</head>
<body>
<div id="test"></div>
<script>
var extJSON = JSON.parse(data);
document.getElementByID("test").innerHTML = extJSON.e1.position;
</script>
</body>
</html>
这是我的JSON文件
{
"e1" :
{
"first_name" : "John",
"last_name" : "Smith",
"age" : 42,
"position" : "mechanic",
"phone" :
{
"home" : "718-111-1111",
"mobile" : "718-222-2222",
"work" : "718-333-3333"
}
},
"e2" :
{
"first_name" : "Jane",
"last_name" : "Smith",
"age" : 34,
"position" : "Investor",
"phone" :
{
"home" : "305-111-1111",
"mobile" : "305-222-2222",
"work" : "305-333-3333"
}
},
"e3" :
{
"first_name" : "Rusty",
"last_name" : "Colon",
"age" : 23,
"position" : "Diver",
"phone" :
{
"home" : "415-111-1111",
"mobile" : "415-222-2222",
"work" : "415-333-3333"
}
},
"e4" :
{
"first_name" : "Anna",
"last_name" : "Spencer",
"age" : 20,
"position" : "Event Planner",
"phone" :
{
"home" : "786-111-1111",
"mobile" : "786-222-2222",
"work" : "786-333-3333"
}
}
}
我只想打印任何值或属性值对。感谢。
答案 0 :(得分:0)
尝试更改脚本标记,如下所示:
<script id="data" type="application/json" src="data.json">
然后参考:
var extJSON = JSON.parse($("#data").html());
希望这有帮助。
答案 1 :(得分:0)
请试试这个 代码
<!DOCTYPE html>
<html>
<head>
<title>Objects 2</title>
<script type="text/javascript" src="data.json"></script>
</head>
<body>
<div id="test"></div>
<script>
var extJSON = data;
document.getElementById("test").innerHTML = extJSON.e1.position;
// it is getElementById not getElementByID. it is case sensitive.
</script>
</body>
</html>
根据您的代码data.json
文件应该像
data= {
"e1" :
{
"first_name" : "John",
"last_name" : "Smith",
"age" : 42,
"position" : "mechanic",
"phone" :
{
"home" : "718-111-1111",
"mobile" : "718-222-2222",
"work" : "718-333-3333"
}
},
"e2" :
{
"first_name" : "Jane",
"last_name" : "Smith",
"age" : 34,
"position" : "Investor",
"phone" :
{
"home" : "305-111-1111",
"mobile" : "305-222-2222",
"work" : "305-333-3333"
}
},
"e3" :
{
"first_name" : "Rusty",
"last_name" : "Colon",
"age" : 23,
"position" : "Diver",
"phone" :
{
"home" : "415-111-1111",
"mobile" : "415-222-2222",
"work" : "415-333-3333"
}
},
"e4" :
{
"first_name" : "Anna",
"last_name" : "Spencer",
"age" : 20,
"position" : "Event Planner",
"phone" :
{
"home" : "786-111-1111",
"mobile" : "786-222-2222",
"work" : "786-333-3333"
}
}
};
希望它适合你。