JSON String inside a JSON

moustacheman picture moustacheman · Oct 7, 2014 · Viewed 42.1k times · Source

I want to create a JSON string inside a JSON request. Here is my code,

Fiddle

JS

var x = {
    a: 1,
    b: 'a sample text',
};

var request = {
    t: JSON.stringify(x),
    c: 2,
    r: 'some text'
};

console.log(request);

Can someone help me how to escape the double quotes?

Console

Object {
  t: "{"a":1,"b":"a sample text"}", //This creates a problem, double quotes inside double quotes.
  c: 2, 
  r: "some text"
}

Thanks in advance.

Answer

Bergi picture Bergi · Oct 7, 2014

There is no problem. It's just your console.log that shows all strings by simply delimiting with ".

As you say this request object is used in a JSON request, where it will be JSON.stringifyed another time, with the valid result

{"t":"{\"a\":1,\"b\":\"a sample text\"}","c":2,"r":"some text"}