Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从python中的嵌套JSON文件访问值_Python_Json - Fatal编程技术网

从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的迭代器

非常感谢。我没注意到“账户”是一个列表。