Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

javascript - JSON.parse string with quotes

I have this:

JSON.parse('{"130.00000001":{"p_cod":"130.00000001","value":"130.00000001 HDD Upgrade to 2x 250GB HDD 2.5" SATA2 7200rpm"}}');

JSONLint says it's perfectly valid json. But on execution I have a JSON.parse error.

But, if I change my code to:

    JSON.parse('{"130.00000001":{"p_cod":"130.00000001","value":"130.00000001 HDD Upgrade to 2x 250GB HDD 2.5" SATA2 7200rpm"}}');

(note the double backslash)

It works, but now JSONLint says invalid json.

Can someone help to understand this behavior?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's a difference between the wire format, and what you have to write in your code to get the wire format. When you declare this in code you need the double- in your literal so the string gets a single backslash (otherwise it will interpret " as an escape sequence for just declaring a " and put that in your string). If you print out the value of the literal you will see a single backslash.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...