简体   繁体   English

如何解析python中的json嵌套字典?

[英]how to parse json nested dict in python?

I'm trying to work with json file stored locally. 我正在尝试使用本地存储的json文件。 That is formatted as below: 格式如下:

{  
   "all":{  
      "variables":{  
         "items":{  
            "item1":{  
               "one":{  
                  "size":"1"
               },
               "two":{  
                  "size":"2"
               }
            }
         }
      }
   }
}

I'm trying to get the value of the size key using the following code. 我正在尝试使用以下代码获取size键的值。

with open('path/to/file.json','r') as file:
  data = json.load(file)
itemParse(data["all"]["variables"]["items"]["item1"])

def itemParse(data):
   for i in data:
   # also tried for i in data.iterkeys():
       # data has type dict while i has type unicode
       print i.get('size')
       # also tried print i['size']

got different errors and nothing seems to work. 出现了不同的错误,似乎没有任何效果。 any suggestions? 有什么建议么?

also, tried using json.loads got error expect string or buffer 另外,尝试使用json.loads得到错误期望字符串或缓冲区

When you iterate over data you are getting the key only. 当您遍历data您只会得到密钥。 There is 2 ways to solve it. 有两种解决方法。

def itemParse(data):
   for i, j in data.iteritems():
       print j.get('size')

or 要么

def itemParse(data):
   for i in data:
       print data[i].get('size')

First, use json.loads() . 首先,使用json.loads()

data = json.loads(open('path/to/file.json','r').read())

Second, your for loop should be changed to this 其次,您的for循环应更改为此

for k,v in data.iteritems():
    print data[k]['size']

Regarding the error expect string or buffer , do you have permissions to read the json file? 关于error expect string or buffer ,您是否有权读取json文件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM