-1

I'm trying to create a string in javascript which needs to be valid JSON the string is

{"query":"FOR u IN Countries RETURN {\"_key\":u._key}"}

I keep going around in circles as to how i can include the \ character given its also used to escape the quote character. can anyone help ?

Sébastien
  • 11,860
  • 11
  • 58
  • 78
user1305541
  • 205
  • 1
  • 4
  • 14

3 Answers3

3

Escape the backslash itself:

{"query":"FOR u IN Countries RETURN {\\\"_key\\\":u._key}"}

First pair of backslashes represents '\' symbol in the resulting string, and \" sequence represents a double quotation mark ('"').

raina77ow
  • 103,633
  • 15
  • 192
  • 229
0

Use \\ for double quoted strings

i.e.

var s = "{\"query\":\"FOR u IN Countries RETURN {\\\"_key\\\":u._key}\"}";

Or use single quotes

var s = '{"query":"FOR u IN Countries RETURN {\"_key\":u._key}"}';
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
  • 1
    It's JavaScript, not PHP/Perl; using single quotation marks won't affect interpolation rules, because, well, there are none. ) – raina77ow Sep 08 '13 at 11:53
  • for what i know escaping is done with one backslash not two ( two means you want the charecter "\" in the string – Liran Sep 08 '13 at 12:07
0

Let JSON encoder do the job:

> s =  'FOR u IN Countries RETURN {"_key":u._key}'
"FOR u IN Countries RETURN {"_key":u._key}"

> JSON.stringify({query:s})
"{"query":"FOR u IN Countries RETURN {\"_key\":u._key}"}"
georg
  • 211,518
  • 52
  • 313
  • 390