Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON String inside a JSON

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.

like image 669
moustacheman Avatar asked Oct 07 '14 14:10

moustacheman


People also ask

Can you have a JSON within a JSON?

Objects can be nested inside other objects. Each nested object must have a unique access path.

Can you use inside a JSON string?

JSON is purely a string with a specified data format — it contains only properties, no methods. JSON requires double quotes to be used around strings and property names. Single quotes are not valid other than surrounding the entire JSON string.

What is nested JSON?

Nested JSON is a JSON file with a big portion of its values being other JSON objects. Compared with Simple JSON, Nested JSON provides higher clarity in that it decouples objects into different layers, making it easier to maintain.


1 Answers

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"}
like image 181
Bergi Avatar answered Sep 20 '22 18:09

Bergi