如何达到嵌套字典值中的嵌套?

时间:2019-12-08 18:30:01

标签: python arrays json nested

{
'data':[
    "firstName": "Jane",
    "lastName": "Doe",
    "hobbies": ["running", "sky diving", "singing"],
    "age": 35,
    "children": [
        {
            "firstName": "Sandy,
            "age": 6
            "values":[
                       {
                      'value' :908
                        } 
                      ]
        },
        {        
            "firstName": "Alice",
            "age": 7
            "values":[
                       {
                      'value' :0123
                        } 
                      ]
        }
        {        
            "firstName": "Dany",
            "age": 8
            "values":[
                       {
                      'value' :0193
                        } 
                      ]
        }
    ]
}

**这是我的json文件。我尝试获取每个块的名字,值和年龄并编写数据库。**我尝试了很多事情,但无法运行..

.
.
results=r.json()

for k in results['data']:
  for k1 in k['children']:
   data={"firstname":k1['firstName']....?Values?)

如何以一种json格式获取每个块值和每个值?

1 个答案:

答案 0 :(得分:0)

我相信您的示例来自网络。但是正如Alberto Poljak和fizzybear指出的那样,您的json格式已损坏。

我在这里corrections - screenshot处进行了更正,并且以这种格式可以正常工作:

{
"data":
{
    "firstName": "Jane",
    "lastName": "Doe",
    "hobbies": ["running", "sky diving", "singing"],
    "age": 35,
    "children": [
        {
            "firstName": "Sandy",
            "age": 6,
            "values":[
                       {
                      "value" :908
                        } 
                      ]
        },
        {        
            "firstName": "Alice",
            "age": 7,
            "values":[
                       {
                      "value" :123
                        } 
                      ]
        },
        {        
            "firstName": "Dany",
            "age": 8,
            "values":[
                       {
                      "value" :193
                        } 
                      ]
        }
    ]
  }
}

如果将以上内容保存在文件“ family.json”中,则此示例代码应该可以正常工作:

import json

with open('family.json') as json_file:
    data = json.load(json_file)
    p = data['data']['children']
    for r in p:
        print('First name: %s' % r['firstName'])
        print('Age: %d' % r['age'])            
        print('')

要快速查看json文件,您可以使用例如https://codebeautify.org/jsonviewer,您可以在其中进行验证或以树形结构等形式查看其内容。