-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,376
  • 11
  • 52
  • 73
user1305541
  • 205
  • 1
  • 2
  • 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
  • 99,006
  • 14
  • 190
  • 222
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
  • 57,599
  • 16
  • 82
  • 120
  • 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
  • 204,715
  • 48
  • 286
  • 369