AldoTheApache AldoTheApache - 4 months ago 11
JSON Question

Append keys and values to one JSON object from multiple JSON files

I'm currently working with three json files.

master.json

{
"master":[
{
"sport": "soccer",
"id": 1
},
{
"sport": "football",
"id": 2
}
]
}


data1.json

{
"soccer": {
"players": 11
},
"football": {
"players": 12
}
}


data2.json

{
"soccer": {
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
},
"football": {
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
}
}


What I'd like to do is combine attributes from each sport in each json file into the
master.json
.

This is what I'm looking for:

{
"master":[
{
"sport": "soccer",
"id": 1,
"players": 11,
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}

},
{
"sport": "football",
"id": 2,
"players": 12,
"stadiums": {
"away": "StadiumA",
"home": "StadiumB"
}
}
]
}


Ideally, I'd like to be able to include a conditional where the sport value in
data1
and
data2
must match what is in
master.json
to do the appending. So, if "baseball" is in
data1
and
data2
but not
master
, then it is not included.

I've tried using
underscore
in JavaScript and
json
in Python but to no luck. I can't seem to find a way to loop through all three json files to have them talking to each other, especially to see if the sport matches.

Any help would be appreciate. I'll also do my best to clarify and confusion.

Answer

Just to demonstrate the relative finesse of Python, I'll throw in a solution:

import json
from collections import OrderedDict

with open('master.json') as m, open('data1.json') as d1, open('data2.json') as d2:
    master = json.load(m, object_pairs_hook=OrderedDict)
    data1 = json.load(d1, object_pairs_hook=OrderedDict)
    data2 = json.load(d2, object_pairs_hook=OrderedDict)

for i, obj in enumerate(master['master']):
    d1, d2 = data1.get(obj['sport']), data2.get(obj['sport'])
    if d1:
        master['master'][i].update(d1)
    if d2:
        master['master'][i].update(d2)

print(json.dumps(master,indent=2))

Output:

{
  "master": [
    {
      "sport": "soccer",
      "id": 1,
      "players": 11,
      "stadiums": {
        "away": "StadiumA",
        "home": "StadiumB"
      }
    },
    {
      "sport": "football",
      "id": 2,
      "players": 12,
      "stadiums": {
        "away": "StadiumA",
        "home": "StadiumB"
      }
    }
  ]
}
Comments