JSON解析错误:字符串未终止 [英] JSON Parse error: Unterminated string

查看:354
本文介绍了JSON解析错误:字符串未终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JSON解析函数中转义引号时遇到了一个常见问题.如果存在转义的引号(在这种情况下为"test"),则会导致以下错误"SyntaxError:JSON解析错误:未终止的字符串".

I've met an usual problem when escaping a quote within the JSON parse function. If the escaped quote is present, in this case 'test"', it causes the following error 'SyntaxError: JSON Parse error: Unterminated string'.

var information = JSON.parse('[{"-1":"24","0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[""],"12":"","13":"","14":"test\""}]');

JSON Lint验证JSON是否有效.

JSON Lint validates the JSON as valid.

推荐答案

"test\\""

var information = JSON.parse('[{"-1":"24","0":"","1":"","2":"","3":"0.0000","4":"","5":"0.00","6":"0.00","7":"1.00","8":"0","9":"false","10":"false","11":[""],"12":"","13":"","14":"test\\""}]');

document.body.innerHTML = '<pre>' + JSON.stringify(information, null, 4) + '</pre>';

第一个反斜杠会在javascript字符串文字中转义第二个反斜杠. 第二个反斜杠转义了JSON字符串文字中的引号.

The first backslash escapes the second backslash in the javascript string literal. The second backslash escapes the quote in the JSON string literal.

因此它被解析了两次,并且需要转义两次.

So it's parsed twice, and needs escaping twice.

因此,即使它是有效的JSON,您也需要为JavaScript字符串文字使用一个转义符,以转义JSON中使用的转义符.

So even if it's valid JSON, you'll need one escape for javascript string literals that escapes the escape used in JSON.

这篇关于JSON解析错误:字符串未终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆