【问题标题】:Need help adding to a JSON dict in python3需要帮助添加到 python3 中的 JSON 字典
【发布时间】:2019-04-01 00:01:36
【问题描述】:

我一直在研究一段需要添加到字典末尾的鳕鱼。 (字典是一些 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)

【问题讨论】:

    标签: json python-3.x dictionary


    【解决方案1】:

    由于data['user'] 是一个数组,你可以追加到它上面。

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

    这应该会产生您正在寻找的格式。

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

    【讨论】:

      【解决方案2】:

      你可以试试:

      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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-30
        • 1970-01-01
        相关资源
        最近更新 更多