16

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?

Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
mjsilva
  • 1,327
  • 3
  • 13
  • 21

1 Answers1

20

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.

Dean Povey
  • 9,256
  • 1
  • 41
  • 52
  • Tks Dean, I think I got to first escape the javascript and then the JSON. So assuming this is coming from PHP how can I "double" escaping it: I've tried this: str_replace('\"','\\"', $json) but it's not working. – mjsilva Jun 18 '10 at 02:54
  • 11
    Got it: str_replace('\\"','\\\\"', $json) Today I learn that there is also a escaping hell :) – mjsilva Jun 18 '10 at 02:58