9

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?

4
  • 2
    That is not JSON. Those are javascript object literals. Commented Jan 26, 2011 at 19:25
  • @patrick dw as long as you don't add objects other than strings, arrays, numbers, hashes and nulls, aren't they interchangeable? Commented Jan 26, 2011 at 19:28
  • 1
    @Radek S: No. JSON is a data exchange format that happens to be a subset of JavaScript object literal notation. JSON is language independent. This might not be the best analogy, but consider XML: XML can also be used as data exchange format. Often it is transformed into DOM. So DOM can be used to represent an XML document. Same for JSON and objects in JavaScript. The only difference is that JSON can be "naturally" converted to JavaScript objects. Commented Jan 26, 2011 at 19:29
  • @Felix is right. JSON data is a string of characters that follow the JSON specification. Commented Jan 26, 2011 at 19:30

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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"}';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.