如何在python中解析json嵌套的dict?

问题描述:

我正在尝试使用本地存储的json文件。这是格式化如下:如何在python中解析json嵌套的dict?

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

我想要使用下面的代码获取大小关键的值。

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'] 

得到了不同的错误,似乎没有任何工作。有什么建议么?

也尝试使用json.loads遇到错误预期字符串或缓冲区

+0

在您的打印行上使用数据[i] ['size']。 –

当你遍历data你得到只是关键。有两种方法可以解决它。

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

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

感谢毛罗!但我想知道为什么我不能得到相同的结果,如果我打印i.get('大小')?不像第二个例子那样再次使用数据? – tkyass

+0

正如我在回答中所说的,当你迭代字典时,它会检索密钥。所以你要在字符串中使用'get'方法。 –

+0

非常感谢毛罗! – tkyass

首先,使用json.loads()

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

其次,你的for循环应改为此

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

关于error expect string or buffer,你是否有权限读取JSON文件?