最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I add JSON object as new level to another JSON object? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 26, 2011 at 19:24 jpkeisalajpkeisala 8,9168 gold badges32 silver badges40 bronze badges 4
  • 2 That is not JSON. Those are javascript object literals. – user113716 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? – user142019 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. – Felix Kling Commented Jan 26, 2011 at 19:29
  • @Felix is right. JSON data is a string of characters that follow the JSON specification. – user113716 Commented Jan 26, 2011 at 19:30
Add a comment  | 

2 Answers 2

Reset to default 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.

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"}';
发布评论

评论列表(0)

  1. 暂无评论