我已经阅读了这篇帖子,但我仍然不知道发生了什么。
根据大多数JSON在线数据检查器,我的var“text”是有效的,但是当我执行解析时,它没有做任何事情。
以下是一个示例代码:
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
var text = '{
"zipcodes": [
{
"zip": "22312",
"city": "Alexandria",
"state": "VA"
},
{
"zip": "22030",
"city": "Fairfax",
"state": "VA"
},
{
"zip": "22301",
"city": "Tyson's Corner",
"state": "VA"
},
{
"zip": "20148",
"city": "Ashburn",
"state": "VA"
}
]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.zipcodes[1].zip + " " + obj.zipcodes[1].city;
</script>
</body>
</html>
答案 0 :(得分:3)
您有两个问题:
JavaScript不支持多行字符串而不用连续符号标记每一行(在行尾通过\
)。我已经在我的例子中完成了这个,但是将JSON包含在一行中真的更容易。
您对字符串使用单引号,但您的字符串包含未转义的'
。逃避它,你很好。
var text = '{ \
"zipcodes": [\
{ \
"zip": "22312", \
"city": "Alexandria", \
"state": "VA" \
}, \
{ \
"zip": "22030", \
"city": "Fairfax", \
"state": "VA" \
}, \
{ \
"zip": "22301", \
"city": "Tyson\'s Corner", \
"state": "VA" \
}, \
{ \
"zip": "20148", \
"city": "Ashburn", \
"state": "VA" \
} \
]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.zipcodes[1].zip + " " + obj.zipcodes[1].city;
<div id='demo'></div>
答案 1 :(得分:2)
您必须将json放在一行并转义'。
“泰森的角落”http://jsbin.com/xumiba/1/edit?html,js,console,output
var text = '{ "zipcodes": [ { "zip": "22312", "city": "Alexandria", "state": "VA" }, { "zip": "22030", "city": "Fairfax", "state": "VA" }, { "zip": "22301", "city": "Tyson\'s Corner", "state": "VA" }, { "zip": "20148", "city":"Ashburn", "state": "VA" }]}';
答案 2 :(得分:0)
你需要在每个字符串新行的末尾添加\并转义'字符。这样的事情会做:
var text = '{\
"zipcodes": [\
{\
"zip": "22312",\
"city": "Alexandria",\
"state": "VA"\
},\
{\
"zip": "22030",\
"city": "Fairfax",\
"state": "VA"\
},\
{\
"zip": "22301",\
"city": "Tyson\'s Corner",\
"state": "VA"\
},\
{\
"zip": "20148",\
"city": "Ashburn",\
"state": "VA"\
}\
]}';
obj = JSON.parse(text);
console.log(obj.zipcodes[1].zip + " " + obj.zipcodes[1].city);
document.getElementById("demo").innerHTML =
obj.zipcodes[1].zip + " " + obj.zipcodes[1].city;
这是一个jsfiddle链接: