user9214020
user9214020

Reputation:

Need help adding to a JSON dict in python3

I've been working on a piece of cod that needs to add to the end of a dict. (the dict being some JSON) The main issue I have been having is that it's not adding to the dictionary the way I wish.

Here is my code for adding to the dict:

with open("data.json", "r") as read_file:
        data = json.load(read_file)

data['user'] = str(data['user']) + "username: " + a

with open("data.json", 'w') as f:
        json.dump(data, f)

Here is the JSON:

{"user": [
    {"username": "a", "data": "a"},
    {"username": "b", "data": "b"},
    {"username": "c", "data": "c"}
    ]}

The result I expected:

{"user": [
    {"username": "a", "data": "a"},
    {"username": "b", "data": "b"},
    {"username": "c", "data": "c"},
    {"username": "d"}
    ]}

The result I got:

{"user": [
    {"username": "a", "data": "a"},
    {"username": "b", "data": "b"},
    {"username": "c", "data": "c"}
    ]}
{"username": "d"}

I think it's how i'm formatting the data['user'] = str(data['user']) + "username: " + a line, but I am having issues coming up with how to format it otherwise. Thanks for any answers!

Edit: here was the complete working code:

with open("data.json", "r") as read_file:
        data = json.load(read_file)

    data['user'].append({"username": a})

    with open("data.json", 'w') as f:
        json.dump(data, f)

Upvotes: 1

Views: 93

Answers (2)

Bhupesh lad
Bhupesh lad

Reputation: 400

you can try:

with open("data.json", "r") as read_file:
        data = json.load(read_file)

data['user'].append({'username':'f'})

with open("data.json", 'w') as f:
        json.dump(data, f)

Upvotes: 0

brandonbanks
brandonbanks

Reputation: 1295

Since data['user'] is an array, you can append to it.

data['user'].append({'username': a})

This should result in the format you are looking for.

>>> data
{'user': [
    {'username': 'a', 'data': 'a'},
    {'username': 'b', 'data': 'b'},
    {'username': 'c', 'data': 'c'},
    {'username': 'd'}
]}

Upvotes: 1

Related Questions