Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add JSON object as new level to another JSON object?

I have a code that gets in the end collection of two JSON objects, something like this.

var jsonL1 = {"holder1": {}}
var jsonL2 = {"section":"0 6","date":"11/12/13"}

I would like to insert jsonL2 inside jsonL1.holder1 and merge it to one JSON object.

Desired output

{
    "holder1": {
        "section": "0 6",
        "date": "11/12/13"
    }
}

How can I do that?

like image 715
jpkeisala Avatar asked Jan 26 '11 19:01

jpkeisala


2 Answers

It is as easy as:

L1.holder1 = L2

I removed the "json" from the variable names, as @patrick already said, you are dealing not with "JSON objects" but with object literals.

See also: There is no such thing as a JSON object

You also might want to learn more about objects in JavaScript.

like image 73
Felix Kling Avatar answered Sep 21 '22 00:09

Felix Kling


If you want the first object to reference the second, do this:

jsonL1.holder1 = jsonL2;

If you wanted a copy of the second in the first, that's different.

So it depends on what you mean by merge it into one object. Using the code above, changes to jsonL2 will be visible in jsonL1.holder, because they're really just both referencing the same object.


A little off topic, but to give a more visual description of the difference between JSON data and javascript object:

    // this is a javascript object
var obj = {"section":"0 6","date":"11/12/13"};

    // this is valid JSON data
var jsn = '{"section":"0 6","date":"11/12/13"}';
like image 27
user113716 Avatar answered Sep 20 '22 00:09

user113716