Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would like to create a list of dictionaries in my JSON file. The problem, though, is that JSON does not append new data properly. Here is my code:

import json

json_data = [
    {
    'name': 'Luke',
    'age': 27
    },
    {
    'name': 'Harry',
    'age': 32
    },
    ]
with open('data.json', 'a+') as file:
    json.dump(json_data, file)

JSON just creates another whole list at each appending attempt:

[
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32}
][
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32}
][
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32}
]

I want to have one single list that holds all these dictionaries. Here's an example of how it SHOULD be like ideally:

[
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32},
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32},
    {"name": "Luke", "age": 27}, 
    {"name": "Harry", "age": 32},
]

How do I create something like that? Thank you for all your help! :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
232 views
Welcome To Ask or Share your Answers For Others

1 Answer

Quick fix solution with eval():

import json

json_data = [
    {
    'name': 'Luke',
    'age': 27
    },
    {
    'name': 'Harry',
    'age': 32
    },
    ]

with open('data.json', 'r+') as file:  # read and append
    stored_info = eval(file.readline())  # using eval() to convert list in file to an actual list
    for i in stored_info:
        json_data.append(i)
    file.seek(0)  # clear file
    json.dump(json_data, file)

However, this will only work if data.json exists and already contains information. You might have to check if data.json exists(which means there will already be information if only program edits data.json):

...
try: 
    with open('data.json', 'r+') as file:  # read and append
        stored_info = eval(file.readline())  # using eval() to convert list in file to an actual list
        for i in stored_info:
            json_data.append(i)
        file.seek(0)  # clear file
        json.dump(json_data, file)
except:  # data.json doesn't exist
    with open('data.json', 'w') as file:
        json.dump(json_data, file)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...