Home > Software engineering >  Nest a Json in Speech Marks
Nest a Json in Speech Marks

Time:12-14

I have a JSON that I'd like to nest into another JSON. Is this possible? Problem I'm facing is when I add Json #2 to #1 is gives me a formatting error.

JSON #1: {"home":"This a sentence about home", "json":"<ADD JSON HERE>"}

JSON #2:

{
    "homepage": {
        "heading": [
            {"h1":"Sentence for H1!"},
            {"description":"Description about us"},
            {"button1":"Learn More"},
        ],
}

What I've tried:

{"home":"This a sentence about home", "json":" { "homepage": {"heading": [ {"h1":"Sentence for H1!"},{"description":"Description about us"},{"button1":"Learn More"},],}"}

CodePudding user response:

(If you are using JavaScript)

If you pass JSON to JSON.stringify it will escape your JSON.

You can then insert the escaped JSON in to your original JSON.

So:

 const jsonToInsert = {
    "homepage": {
       "heading": [
           {"h1":"Sentence for H1!"},
           {"description":"Description about us"},
           {"button1":"Learn More"}
       ]
     }
 };
 const stringifiedJson = JSON.stringify(jsonToInsert);
 const completeJson = {"home":"This a sentence about home", "json": stringifiedJson}

Should work - sorry if there’s typos, replying on my phone.

CodePudding user response:

The second JSON isn't valid (extra commas and missing }), but this is:

{
    "homepage": {
        "heading": [
            {"h1":"Sentence for H1!"},
            {"description":"Description about us"},
            {"button1":"Learn More"}
        ]
    }
}

This is how to embed it as a string:

{
  "home": "This a sentence about home",
  "json": "{\"homepage\": {\"heading\": [{\"h1\": \"Sentence for H1!\"}, {\"description\": \"Description about us\"}, {\"button1\": \"Learn More\"}]}}"
}
  •  Tags:  
  • json
  • Related