OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Merge json objects present under duplicate keys

  • Thread starter Thread starter sjko5
  • Start date Start date
S

sjko5

Guest
I have a json file like this:

Code:
{
    "parent1": {
        "child1": "bob"
    },
    "parent1": {
        "child2": "tom"
    },
    "parent2": {
        "child1": "jon"
    }
}

I want to merge the values present under duplicate toplevel keys. So the expected output should be:

Code:
{
    "parent1": {
        "child1": "bob",
        "child2": "tom"
    },
    "parent2": {
        "child1": "jon"
    }
}

Currently I am using the following code to check duplicate keys:

Code:
import json

def check_duplicates(pairs):
    d = {}
    for key, val in pairs:
        if key in d:
            raise ValueError(f"Duplicate key(s) found: {key}")
        else:
            d[key] = val
    return d

filename = "test.json"
with open(filename, "r") as f:
    try:
        data = json.load(f, object_pairs_hook=check_duplicates)
    except ValueError as err:
        print(f"{filename}: Failed to decode: {err}")

Any idea how I can merge them?
<p>I have a json file like this:</p>
<pre class="lang-json prettyprint-override"><code>{
"parent1": {
"child1": "bob"
},
"parent1": {
"child2": "tom"
},
"parent2": {
"child1": "jon"
}
}
</code></pre>
<p>I want to merge the values present under duplicate toplevel keys. So the expected output should be:</p>
<pre class="lang-json prettyprint-override"><code>{
"parent1": {
"child1": "bob",
"child2": "tom"
},
"parent2": {
"child1": "jon"
}
}
</code></pre>
<p>Currently I am using the following code to check duplicate keys:</p>
<pre class="lang-py prettyprint-override"><code>import json

def check_duplicates(pairs):
d = {}
for key, val in pairs:
if key in d:
raise ValueError(f"Duplicate key(s) found: {key}")
else:
d[key] = val
return d

filename = "test.json"
with open(filename, "r") as f:
try:
data = json.load(f, object_pairs_hook=check_duplicates)
except ValueError as err:
print(f"{filename}: Failed to decode: {err}")
</code></pre>
<p>Any idea how I can merge them?</p>
 
Top