Merge a JSON with a JSON

Merges two JSON objects and returns the merged result.

Overview

This procedure merges two JSON objects into one. The first JSON object (target) is merged with the second JSON object (object), and the result contains all keys from both objects. The original JSON objects remain unchanged; a new merged object is returned.

Input

Concept
Type
Description
Required
Default

target

json

The first JSON object

Yes

N/A

object

json

The second JSON object which will be merged with the first

Yes

N/A

Output

Concept
Description

json

The final merged JSON object

Examples

1. Simple merge with non-overlapping keys

This example merges two JSON objects where some keys overlap. The merged result would be: {"address": "Bangalore", "age": 28, "company": "Kognitos", "name": "john"}. Note that in the basic implementation, the "company" field from json2 would overwrite json1's value.

create a empty json
use the above as json1
set the json1's name to "john"
set the json1's age to 28
set the json1's company to "Kognitos"
create an empty json
use the above as json2
set the json2's company to "XYZ"
set the json2's address to "Bangalore"
merge the json1 with the json2

2. Verifying original objects remain unchanged

This example verifies that the original JSON objects are not modified by the merge operation.

the json1
the json2

3. Nested JSON Merge

For nested JSON structures like:

  • json1: {"company": "XYZ", "address": {"street": "State", "pets": ["Garfield", "Opus"]}}

  • json2: {"age": 28, "name": "john", "company": "Kognitos", "address": {"number": 123, "street": "Main", "pets": ["Alf"]}}

The new JSON implementation's recursive merge produces: {"age": 28, "name": "john", "company": "XYZ", "address": {"number": 123, "street": "State", "pets": ["Alf", "Garfield", "Opus"]}}

This demonstrates:

  • Nested objects are merged recursively

  • Arrays are concatenated (not replaced)

  • Primitive values from json1 overwrite those in json2

merge the json1 with the json2

4. Hierarchical JSON example

This example shows a complete workflow of creating two JSON objects and merging them. The final result would be: {"name": "John", "age": 30, "height": 182, "city": "Bangalore"}

create an empty json
use the above as the targetjson
set the targetjson's name to "John"
set the targetjson's age to "30"
create an empty json
use the above as the objectjson
set the objectjson's height to 182
set the objectjson's city to "Bangalore"
merge the target json with the object json

5. Merge with duplicate key behavior

In case of duplicate keys, the value from the second JSON (object) overwrites the value from the first JSON (target).

For example:

  • target json: {"name": "John", "age": 30}

  • object json: {"place": "USA", "age": 31}

  • final result: {"name": "John", "place": "USA", "age": 31}

The "age" field is updated to 31 from the object json.

Last updated

Was this helpful?