Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.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
对于JSON对象python的每个循环_Python_Json - Fatal编程技术网

对于JSON对象python的每个循环

对于JSON对象python的每个循环,python,json,Python,Json,好吧,我正在努力解析我的JSON对象。 我的目标是获取特定的JSON键并返回其值 JSON文件 { "files": { "resources": [ { "name": "filename", "hash": "0x001" }, { "name": "filename2", "hash": "0x002" } ] } } 我开发了一个函数,可以解析上面的J

好吧,我正在努力解析我的JSON对象。 我的目标是获取特定的JSON键并返回其值

JSON文件

{
  "files": {
    "resources": [
      {
        "name": "filename",
        "hash": "0x001"
      },
      {
        "name": "filename2",
        "hash": "0x002"
      }
    ]
  }
}
我开发了一个函数,可以解析上面的JSON代码

功能

def parsePatcher():
    url = '{0}/{1}'.format(downloadServer, patcherName)
    patch = urllib2.urlopen(url)
    data = json.loads(patch.read())
    patch.close()
    return data
好的,现在我想做一个foreach语句,它打印出
资源“:[]
对象中的每个名称和散列

Foreach语句

for name, hash in patcher["files"]["resources"]:
    print name
    print hash
但它只打印“name”和“hash”,而不是“filename”和“0x001”


我在这里做了什么不正确的事情吗?

使用
name,hash
作为
循环目标,您正在解包字典:

>>> d = {"name": "filename",  "hash": "0x001"}
>>> name, hash = d
>>> name
'name'
>>> hash
'hash'
for resource in patcher["files"]["resources"]:
    print resource['name']
    print resource['hash']
这是因为字典上的迭代只生成键:

>>> list(d)
['name', 'hash']
解包使用迭代生成要分配给目标名称的值

即使在Python3.3和更新版本上,在默认情况下启用了散列随机化,这两个键的顺序也同样可以颠倒

只需使用一个名称将词典分配给,并使用该词典上的订阅:

>>> d = {"name": "filename",  "hash": "0x001"}
>>> name, hash = d
>>> name
'name'
>>> hash
'hash'
for resource in patcher["files"]["resources"]:
    print resource['name']
    print resource['hash']

问题似乎是您有一个字典列表,首先获取列表中的每个元素,然后向元素(即字典)询问key name和hash的值

编辑:这是测试和工作

mydict = {"files": { "resources": [{  "name": "filename",  "hash": "0x001"},{  "name": "filename2",  "hash": "0x002"}]} }

for element in mydict["files"]["resources"]:
  for d in element:
    print d, element[d]

因此,您打算做的是:

for dic in x["files"]["resources"]:
    print dic['name'],dic['hash']

您需要在该数组资源中的那些字典上进行迭代。

如果您在其中有多个文件和多个资源。这个广义解是有效的

for keys in patcher:
     for indices in patcher[keys].keys():
             print(patcher[keys][indices])
检查myside的输出

for keys in patcher:
...     for indices in patcher[keys].keys():
...             print(patcher[keys][indices])
...
[{'hash': '0x001', 'name': 'filename'}, {'hash': '0x002', 'name': 'filename2'}]

请注意,JSON是一种传输格式。解析后,您就只有Python对象了。谢谢。这是完美的解决方案!:)啊,不,它会工作,但不会产生预期的输出。行动已经走了这么远,他们已经有了名单。您创建了一个复杂的循环版本的
patcher[“files”][“resources”]
表达式,但没有在该列表上循环。我并不是说您的答案是错误的,我概括了多个元素。。。对于该循环,应使用。。。