简体   繁体   English

json解析包含特殊字符的字符串时发生意外的令牌错误

[英]Unexpected token error while json parsing for string containing special characters

On trying to parse the following string on titanium Studio for mobile app project, I get the 在尝试在Titan Studio for mobile应用程序项目上解析以下字符串时,我得到了

error: Unexpected token at profileSkills":"Analysis 错误:profileSkills上的意外令牌“:”分析

des='[{"jobId":0,"jobPositionName":"NA","companyId":0,"companyDisplayName":"NA","profileSkills":"Analysis\r\nAnalysis\r\nQuality Assurance\r\nProject Management\r\nProgrammer Analyst\r\n"}]';
desjson=JSON.parse(des);

Can anyone help me , whether I can parse strings containing escape charaters using JSON. 任何人都可以帮助我,是否可以使用JSON解析包含转义字符的字符串。

If not, could you tell me the procedure to it. 如果没有,您能告诉我有关程序。

You need to encode the special characters with double-backslashes, because the JSON parser will expect them to be escaped. 您需要使用双反斜杠对特殊字符进行编码,因为JSON解析器将期望对这些特殊字符进行转义。

var des='[{"jobId":0,"jobPositionName":"NA","companyId":0,"companyDisplayName":"NA","profileSkills":"Analysis\\r\\nAnalysis\\r\\nQuality Assurance\\r\\nProject Management\\r\\nProgrammer Analyst\\r\\n"}]';

If you are actually declaring the JSON string as a JavaScript string literal, then you have to account for the fact that when the JavaScript parser sees those escaped characters, it'll build a string with the real carriage return and line feed characters. 如果实际上是将JSON 字符串声明为JavaScript字符串文字,则必须考虑以下事实:当JavaScript解析器看到这些转义的字符时,它将使用真实的回车符和换行符来构建一个字符串。 The JSON parser coming along after that won't like them. 之后的JSON解析器将不喜欢它们。

If, on the other hand, your JSON is really coming from a server, then the JSON "on the wire" should not have doubled backslashes. 如果,另一方面,你的JSON真的是从“上线”的服务器,则JSON未来应该加倍反斜杠。

I should also note that there's rarely any reason to put a JSON string as a literal in JavaScript code. 我还应注意,几乎没有任何理由将JSON字符串作为文字放入JavaScript代码中。 It might as well be a JavaScript object literal, in most cases. 在大多数情况下,它也可能是JavaScript对象文字。 (I acknowledge that there might be some reason for it, of course.) (我承认,当然可能有某些原因。)

You have two \\r\\ in the string, that should be \\r\\n . 字符串中有两个\\r\\ ,应该为\\r\\n Change those, and it validates as correct JSON. 更改它们,并验证为正确的JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM