JSON 中的字符串未捕获语法错误

string in JSON uncaught syntaxerror

本文关键字:语法 错误 字符串 JSON      更新时间:2023-09-26

我的javascript代码中的JSON对象数组有问题,这是代码

[{"id":"ID", "lat":"LAT", "lon":"LON", "zip":"ZIP", "text":"TEXT"}]

问题出现在"文本"对象中,当字符串包含"in"工作时,它说"未捕获的语法错误:意外令牌非法"这是完整的代码:

[{"id":"1", "lat":"43.19716728250127", "lon":"-119.53125", "zip":"40219", "text":"Testing, Hello World"},{"id":"2", "lat":"46.92025531537451", "lon":"-119.443359375", "zip":"40222", "text":"hello world"},{"id":"3", "lat":"39.16414104768742", "lon":"-82.529296875", "zip":"", "text":"Choice Roof Contractor
<br>Based in Mansfield, OH"}]

你面临的问题是JavaScript不支持多行字符串。确保所有字符串都在一行上。

[{"id":"1", "lat":"43.19716728250127", "lon":"-119.53125", "zip":"40219", "text":"Testing, Hello World"},{"id":"2", "lat":"46.92025531537451", "lon":"-119.443359375", "zip":"40222", "text":"hello world"},{"id":"3", "lat":"39.16414104768742", "lon":"-82.529296875", "zip":", "text":"选择屋顶承包商
总部位于俄亥俄州曼斯菲尔德"}]

这应该是这样的:

[{"id":"1", "lat":"43.19716728250127", "lon":"-119.53125", "zip":"40219", "text":"Testing, Hello World"},{"id":"2", "lat":"46.92025531537451", "lon":"-119.443359375", "zip":"40222", "text":"hello world"},{"id":"3", "lat":"39.16414104768742", "lon":"-82.529296875", "zip":", "text":"Choice 屋顶承包商
总部位于俄亥俄州曼斯菲尔德"}]

一个简单的例子:

// Will NOT work!
var str =  "This is a
multiline string";
// Will work
var str = "This is not a multiline string";
// Will work
var str = "This is a " + 
"multiline string";

这是有效的javascript。在选择屋顶承包商导致问题之后,http://jsfiddle.net/tSRPV/有一个换行符。

var _json = [{
    "id": "1",
    "lat": "43.19716728250127",
    "lon": "-119.53125",
    "zip": "40219",
    "text": "Testing, Hello World"
}, {
    "id": "2",
    "lat": "46.92025531537451",
    "lon": "-119.443359375",
    "zip": "40222",
    "text": "hello world"
}, {
    "id": "3",
    "lat": "39.16414104768742",
    "lon": "-82.529296875",
    "zip": "",
    "text": "Choice Roof Contractor <br>Based in Mansfield, OH"
}];
for (i = 0; i < _json.length; i++) {
    console.log(_json[i].text);
}

在这里摆弄