从python中的嵌套JSON文件访问值
这是我试图在程序中解析的从python中的嵌套JSON文件访问值,python,json,Python,Json,这是我试图在程序中解析的cred.json文件 {"accounts":[ { "id":"1", "username":"user1", "password":"password1" }, { "id":"2", "username":"user2", "p
cred.json
文件
{"accounts":[
{
"id":"1",
"username":"user1",
"password":"password1"
},
{
"id":"2",
"username":"user2",
"password":"password2"
}
]}
这是我使用的代码。这是可行的,但我知道这不是最好的方法
import json
with open('cred.json') as cred_file:
parsed_json = json.load(cred_file)
cred_file.close
for x in range(0,2):
user = parsed_json["accounts"][x]["username"]
password = parsed_json["accounts"][x]["password"]
print user, ":", password
我想做同样的事情,不指定循环的范围。当我尝试对iteritems()
或get()
执行相同操作时,它会给我一个错误,即unicode不支持这些函数
请给我一个更好的方法。
parsed_json
加载了整个dict,其中包含一个键“account”,其值是帐户列表,如dict。因此,不要执行范围+索引查找,而是直接循环帐户列表:
for account in parsed_json["accounts"]:
user = account["username"]
password = account["password"]
print user, ":", password
另外,您不需要cred_file.close
(应该是cred_file.close()
btw),因为它在您使用上下文退出后关闭。正确的方法是:
with open('cred.json') as cred_file:
parsed_json = json.load(cred_file)
for account in parsed_json["accounts"]:
user = account["username"]
password = account["password"]
print user, ":", password
使用Python 3
import json
with open('cred.json') as f:
lines_read = f.readlines()
json_str = ''.join(lines_read)
json_dict = json.loads(json_str)
for account in json_dict['accounts']:
user = account['username']
password = account['password']
print(user, ':', password)
基本思想是使用python的迭代器 非常感谢。我没注意到“账户”是一个列表。