简体   繁体   中英

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.

Problem is, that string is sent to me from a server, I get it via an .xhr() request. 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?

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/

If you quote is part of the string, then it's not 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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