skip to Main Content

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"},],}"}

2

Answers


  1. 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"}
            ]
        }
    }
    

    To embed it as a string, backslash-escape the embedded double-quotes:

    {
      "home": "This a sentence about home",
      "json": "{"homepage": {"heading": [{"h1": "Sentence for H1!"}, {"description": "Description about us"}, {"button1": "Learn More"}]}}"
    }
    
    Login or Signup to reply.
  2. (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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search