JSON or JavaScript Object Notation, is a text-based data interchange format. JSON consists of key value pair with comma separated or an array or mixed both of them. Here an example of JSON:

[sourcecode lang=”javascript”]
var a = {title:’Semurjengkol in the night’, author:’Amir Hamzah’};
[/sourcecode]

Variable [cci]a[/cci] is JSON object which has two keys, [cci]title[/cci] and [cci]author[/cci]. Consider you have another JSON object:

[sourcecode lang=”javascript”]
var b = {book: ‘Puasa Siang Hari’, page: 12};
[/sourcecode]

Our goal is to merge [cci]a[/cci] and [cci]b[/cci] to build new JSON object. There are two methods to merge two JSON Object.

Merge all of keys

Using this method, we combine all of keys from both [cci]a[/cci] and [cci]b[/cci] to build new JSON object which have keys from [cci]a[/cci] and [cci]b[/cci].

[sourcecode lang=”javascript”]
var a = {title:’Semurjengkol in the night’, author:’Amir Hamzah’};
var b = {book: ‘Puasa Siang Hari’, page: 12};
var c = a.merge(b);
console.log(c);
[/sourcecode]

Method [cci]a.merge(b)[/cci] will return new JSON object which have all of keys from [cci]a[/cci] and [cci]b[/cci]. Here is the content of [cci]c[/cci]

[sourcecode lang=”javascript”]
c = {title:’Semurjengkol in the night’, author:’Amir Hamzah’, book: ‘Puasa Siang Hari’, page: 12};
[/sourcecode]

Merge to one root

Another method to merge two JSON object is attach them into one root.

[sourcecode lang=”javascript”]
var a = {title:’Semurjengkol in the night’, author:’Amir Hamzah’};
var b = {book: ‘Puasa Siang Hari’, page: 12};
var c = {};
c[‘a’] = a;
c[‘b’] = b;
console.log(c);
[/sourcecode]

By using this method, the new JSON object [cci]c[/cci] will be like this:

[sourcecode lang=”javascript”]
c = {a: {title:’Semurjengkol in the night’, author:’Amir Hamzah’},
b:{book: ‘Puasa Siang Hari’, page: 12}};
[/sourcecode]


0 Comments

Leave a Reply

Avatar placeholder