需要帮助添加到python3中的JSON字典

时间:2019-04-01 00:01:36

标签: json python-3.x dictionary

我一直在研究需要添加到字典末尾的鳕鱼。 (字典是一些JSON)我遇到的主要问题是它没有按照我希望的方式添加到字典中。

这是我添加到字典中的代码:

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)

这是JSON:

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

我期望的结果:

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

我得到的结果:

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

我认为这是我格式化data['user'] = str(data['user']) + "username: " + a行的方式,但是我在解决如何格式化它方面遇到了问题。感谢您的回答!

编辑:这是完整的工作代码:

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)

2 个答案:

答案 0 :(得分:1)

由于tiny_alien.png是一个数组,因此可以附加到它。

data['user']

这应该导致您正在寻找的格式。

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

答案 1 :(得分:0)

您可以尝试:

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)