Scott Mackenzie
Scott Mackenzie

Reputation: 9

Python generate JSON from two dictionaries

I have two dictionaries in python 3, called a and b which when dumped as JSON come out as below:

a = {"person": 26.94, "car": 99.49, "dog": 50.56}

b = {"filename": "1234.jpg", "model": "model1", "prototxt": "prototxt.txt"}

I need to combine these into the JSON format below but I am a bit lost on the approach in python, so welcome any pointers!

{
"payload": {
    "config": [{
        "model": "model1",
        "filename": "1234.jpg",
        "prototxt": "prototxt.txt"
    }],
    "results": [{
            "object": "person",
            "value": 26.94
        },
        {
            "object": "car",
            "value": 99.49
        },
        {
            "object": "dog",
            "value": 50.56
        }
    ]
 }
}

Upvotes: 0

Views: 549

Answers (1)

D.Griffiths
D.Griffiths

Reputation: 2307

You can achieve this by the following code:

a = {"person": 26.94, "car": 99.49, "dog": 50.56}
b = {"filename": "1234.jpg", "model": "model1", "prototxt": "prototxt.txt"}
a_list= []
for record in a:
    a_list.append({'object':record, 'value':a[record]})

payload = {'config':[b], 'results':a_list}
data = {"payload":payload}

# You can print this in the terminal/notebook with
print json.dumps(data, indent=4)

# Or save with
json_string = json.dumps(data)
with open('/path/to/file/payload.json', 'w') as outfile:
    json.dump(data, outfile)

It's a matter of making entries in dictionaries and packaging them up in strings to add into new higher dictionaries.

Upvotes: 2

Related Questions