【问题标题】:How can i add some element into json file using python?如何使用 python 将一些元素添加到 json 文件中?
【发布时间】:2021-12-26 08:58:43
【问题描述】:

这是 json {"name": ["Juan", "Alex"]}。 如何使用 python 在“名称”中添加一些东西? 提前感谢您的回复。 这是我的代码,他不工作:(

import json

enteredString = str(input())
json_file = 'list_of_workers.json'
data = json.load(open(json_file, "rb"))
data['name'].append(enteredString)
json.dump(data, open(json_file, "wb"))



enteredString = str(input())
json_file = 'list_of_workers.json'
data = json.load(open(json_file, "r"))
data['name'].append(enteredString)
json.dump(data, open(json_file, "w"))
(working_code)

【问题讨论】:

    标签: json python-3.x


    【解决方案1】:
    import json
    
    enteredString = str(input())
    json_file = 'list_of_workers.json' 
    data = json.load(open(json_file, "rb"))
    data['name'].append(enteredString)
    newdata = json.dumps(data, indent=4, sort_keys=True)  
    with open(json_file, 'w') as f:   
        f.write(newdata)
    

    【讨论】:

      猜你喜欢
      • 2014-04-13
      • 2022-11-16
      • 2014-08-01
      • 1970-01-01
      • 2013-01-04
      • 2022-01-20
      • 1970-01-01
      • 2021-05-18
      • 1970-01-01
      相关资源
      最近更新 更多