Extend JSON files with Python

Question:

I looked my problem up on stackoverflow and there are several solutions to my problem which just don’t work in my case.
I want to add a few new entries to my json file.

My json file (data.json):

{
        "blabla1":"dubdub1",
        "blabla2":"dubdub2"
}

My code (using the extend method):

import json

with open('data.json') as json_data_file:
    data = json.load(json_data_file)
result = list()

result.extend(data)
result.extend({'blabla3': 'dubdub3'})
data = result

print(data)

Which gives me an output like:

['blabla1', 'blabla2', 'blabla3']

My code (using the append method):

import json

with open('data.json') as json_data_file:
    data = json.load(json_data_file)
result = list()

result.append(data)
result.append({'blabla3': 'dubdub3'})
data = result

print(data)

Which gives me an output like:

[{'blabla1': 'dubdub1', 'blabla2': 'dubdub2'}, {'blabla3': 'dubdub3'}]

What I need in the end is this:

[{'blabla1': 'dubdub1', 'blabla2': 'dubdub2', 'blabla3': 'dubdub3'}]

So where am I going wrong? I’m sorry if the same question has already been answered, but I couldn’t find something that worked for me. Thank you!

Asked By: Cal Blau

||

Answers:

Is this closer to what you want? A dictionary updated with the new key and value

import json

with open('data.json') as json_data_file:
    data = json.load(json_data_file)
data['blabla3'] = 'dubdub3'
print(data)  # {'blabla1': 'dubdub1', 'blabla2': 'dubdub2', 'blabla3': 'dubdub3'}

EDIT:

To update multiple entries at the same time you can use update

data.update({
    'blabla3': 'dubdub3',
    'blabla4': 'dubdub4',
})
Answered By: Iain Shelvington

Without changing your code much you could achieve your original request like this:

import json

with open('data.json') as json_data_file:
    data = json.load(json_data_file)

data.update({'blabla3': 'dubdub3'})
result = [data]

print(result)

Which will produce your expected result:

[{'blabla1': 'dubdub1', 'blabla2': 'dubdub2', 'blabla3': 'dubdub3'}]

Short explanation:

The method json.load you called created a dictionary object data that looks like this:

{'blabla1': 'dubdub1', 'blabla2': 'dubdub2'}

Then by calling result.append(data) you added the data dictionary as the first citizen in the list object result:

[{'blabla1': 'dubdub1', 'blabla2': 'dubdub2'}]

And every other time you call the append() method you will just add another member to the list:

[{'blabla1': 'dubdub1', 'blabla2': 'dubdub2'}, obj2, obj3, ...]

Instead it seems you wanted to add another key-value pair to the data dictionary as explained in the previous answer

Answered By: matanz
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.