0

I am trying to create a JSON array but it doesn't work:

var test = '{"chapters":[{"id":"test1", "label":"Observation", "handler":"openChapter("observation")"}]}';

I know the problem are the quotes around observation in the handler.

I tried this but it doesn't work either (not surprising):

var test = '{"chapters":[{"id":"test1", "label":"Observation", "handler":"openChapter(\"observation\")"}]}';

How can I do?

Thank you for your help!

Powkachu
  • 2,170
  • 2
  • 26
  • 36

3 Answers3

4

You need to escape it again (\\"), you want the literal \ to be in the string so JSON.parse can read it:

var test = '{"chapters":[{"id":"test1", "label":"Observation", "handler":"openChapter(\\"observation\\")"}]}';
franciscod
  • 992
  • 4
  • 17
1

Well the correct way to escape double quotes (") is indeed a single backslash (\).

However you're creating a variable test as a String and not as a JSON object. If you want to create a JSON object you can do:

var test = {"chapters":[{"id":"test1", "label":"Observation", "handler":"openChapter(\"observation\")"}]};

But if you want to create it as a string for use with JSON.parse for example, you need to escape the backslashes now with another backslash:

var test = '{"chapters":[{"id":"test1", "label":"Observation", "handler":"openChapter(\\"observation\\")"}]}';
var json = JSON.parse(test);

JSON definition of a string:

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.

Strelok
  • 50,229
  • 9
  • 102
  • 115
0

Not sure what you're trying to do ? As I understand it, you want to create in JavaScript datas to be sent in a JSON form ?

Then you should :

  1. create an object literal
  2. transform the JS object in a JSon string

Regarding JS object literals, see this webpage :
http://www.dyn-web.com/tutorials/object-literal/

You can then serialize this object to a JSON string using JSON.stringify().

Another article that is a good read !
http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/