如何在python中添加到json文件

时间:2016-01-17 20:05:17

标签: python json

我可以读取json文件并设置变量所需的信息。我有帐户,我需要能够添加一个帐户,这是我到目前为止的代码:

import json

user = raw_input("User: ")

with open('text.json') as data_file:
    data = json.load(data_file)

code =  data["users"][user]["pass"]
display = data["users"][user]["display"]

print "Password: " + code
print "Display Name - " + display

这可以正常读取文件,这是输出json文件的预期格式:

{
  "users":{
    "User1": {
      "display": "User1",
      "pass": "EzPass123"
    },
    "Richard": {
      "display": "Attack69",
      "pass": "Smith"
    }
  }
}

有人可以告诉我如何将其他帐户添加到字典中已存在的帐户吗?

2 个答案:

答案 0 :(得分:2)

import json

# here you read your new user and his password
user = raw_input("User: ")
display = raw_input("Display name: ")
pwd = raw_input("Pass: ")

with open('text.json') as data_file:
    data = json.load(data_file)
    # update the data dictionary then re-dump it in the file
    data['users'].update({
        user: {
            'display': display,
            'pass': pwd
        }
    })

with open('text.json', 'w') as data_file:
    json.dumps(data, data_file, indent=4)

答案 1 :(得分:0)

这是一个涵盖其他答案中讨论的修复的解决方案:

#!python2
import json

# here you read your new user and his password
user = raw_input("User: ")
display = raw_input("Display name: ")
pwd = raw_input("Pass: ")

with open('text.json') as data_file:
    data = json.load(data_file)
    data['users'][user] = {'display':display,'pass':pwd}

with open('text.json','w') as data_file:
    json.dump(data, data_file, indent=4)

输出:

User: markt
Display name: Mark
Pass: 123

结果:

{
    "users": {
        "markt": {
            "display": "Mark",
            "pass": "123"
        },
        "Richard": {
            "display": "Attack69",
            "pass": "Smith"
        },
        "User1": {
            "display": "User1",
            "pass": "EzPass123"
        }
    }
}