简体   繁体   English

为什么此字符串不解析为JSON?

[英]Why won't this string parse to JSON?

string in question: 有问题的字符串:

'{"images":{"0":"<div style=\\"background:red;width:250px;height:250px;display:block;position:absolute;\\"></div>"}}'

I've tried various combinations of single and double quotes. 我尝试了单引号和双引号的各种组合。 If you plop that string into Chrome's javascript console, into JSON.parse(), it parses fine. 如果您将该字符串放入Chrome的JavaScript控制台,JSON.parse(),则会很好地解析。

Problem is, that string is sent to me from a server, I get it via an .xhr() request. 问题是,该字符串是从服务器发送给我的,我是通过.xhr()请求获得的。 As soon as that step is added, no matter the permutations of single and double quotes I keep getting errors like: 添加该步骤后,无论单引号和双引号的排列如何,我都会不断收到如下错误:

Unexpected Token ' 意外的标记 '

How do I request a string like that and JSON.parse it to an object? 我如何请求这样的字符串并将其JSON.parse到对象?

It should be 它应该是

var jsonstr = '{"images":{"0":"<div style=\"background:red;width:250px;height:250px;display:block;position:absolute;\"></div>"}}'

You use double \\\\ instead of \\ 您使用双\\\\代替\\

There are nice online parsers that can help you debug. 有不错的在线解析器可以帮助您调试。 Eg http://json.parser.online.fr/ 例如http://json.parser.online.fr/

If you quote is part of the string, then it's not json. 如果引用是字符串的一部分,则它不是json。 remove the starting and closing quotes. 删除开始和结束引号。

And there is no reason to double escape the double quotes. 并且没有理由对双引号加倍转义。

You could simply choose, not to use \\" - double quotes and use single quotes instead. I hope you would be rendering this div on html, so even this would be fine 您可以选择不使用\\“-不使用双引号,而使用单引号。我希望您可以在html上呈现此div,所以即使这样也很好

{
    "images": {
        "0": "<div style='background:red;width:250px;height:250px;display:block;position:absolute;'></div>"
    }
}

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

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