Is it possible to wrap json in a json field like a string?

I have json like this:

json1:

{  
    "field1": 111111,
    "field2": "someValue"
}

      

How can I put it in the requestBody field in json2 as a string?

json2:

{  
    "requestBody": json1  
}

      

Something like that:

{  
    "requestBody": "{"field1": 111111,"field2": "someValue"}"
}

      

+3


source to share


5 answers


JSON encoded stuff is just a string. If you want to embed json-in-json then the "internal" json must be json encoded.

eg.



$inner = {"foo":"bar"}
$outer = {"container":"{\"foo\":\"bar\"}"}

      

Now the internal json is no longer json. It's just a string that comes from kinda / sorta, which looks like JSON.

+4


source


As Mark B pointed out, inner quotes must be escaped.

{"requestBody":"{\"field1\":111111,\"field2\":\"someValue\"}"}



Violin:

http://jsfiddle.net/cheoc1zj/

+2


source


It won't be great, but if you base64 encode the JSON payload, you can be sure it won't be parsed unexpectedly.

How to base64 encode with Javascript: http://www.webtoolkit.info/javascript-base64.html

{  
    "requestBody": "eyJmaWVsZDEiOiAxMTExMTEsImZpZWxkMiI6ICJzb21lVmFsdWUifQ=="
}

      

+1


source


something like this (deleted quotes around inner JSON):

{  
    "requestBody": {"field1": 111111, "field2": "someValue"}
}
0


source


Dropping double quoted strings is ugly. Why not use single quotes in inline JSON? For example:

{
    "container":"{'foo':'bar'}"
}

      

0


source







All Articles