[英]I can't parse using JSON using Javascript
I have read the post for this an yet I still don't know what is happening. 我已经阅读了这篇文章,但我仍然不知道发生了什么。
My var "text" is valid according to most JSON online data checker but when I execute the parse it doesn't do anything. 根据大多数JSON在线数据检查器,我的var“文本”有效,但是当我执行解析时,它什么也没做。
Here is an example code: 这是示例代码:
<!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>
You have two issues: 您有两个问题:
JavaScript doesn't support multi-line strings without marking each line with a continuation (via \\
at the end of the line). JavaScript不支持多行字符串,而无需在每行上都标记一个连续符(通过\\
在行末)。 I've done this in my example but it's really easier to include your JSON on a single line. 我已经在示例中完成了此操作,但是将JSON包含在一行中确实更加容易。
You're using single-quotes for your string but your string contains an un-escaped '
. 您在字符串中使用了单引号,但字符串中包含未转义的'
。 Escape it, and you're fine. 逃脱它,你很好。
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>
You have to put the json on one line and escape your '. 您必须将json放在一行上并转义'。
"Tyson\\'s Corner" “泰森角”
http://jsbin.com/xumiba/1/edit?html,js,console,output http://jsbin.com/xumiba/1/edit?html,js,控制台,输出
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" }]}';
You need to add \\ at the end of every string new line and escape the ' character. 您需要在每个字符串的新行末添加\\并转义'字符。 Something like this will do: 这样的事情会做:
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;
Here is a jsfiddle link: 这是一个jsfiddle链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.