Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

Python 字典嵌套循环遍历

这是从接口获取到的json数据

{
*   "code":"10000",
*   "charge":false,
*   "remain":0,
*   "msg":"查询成功",
*   "result":{
    *   "status":0,
    *   "msg":"ok",
    *   "result":{
        *   "total":1384,
        *   "num":5,
        *   "list":[
             {
                *   "id":1,
                *   "classid":2,
                *   "name":"炸茄盒",
                *   "peoplenum":"3-4人",
                *   "preparetime":"10分钟内",
                *   "cookingtime":"10-20分钟",
                *   "content":"炸茄盒外焦里嫩,入口不腻,咬上一口,淡淡的肉香和茄子的清香同时浮现,让人心动不已。",
                *   "pic":"http://123123~~~~/recipe/upload/20160719/115137_60657.jpg",
                *   "tag":"健脾开胃,儿童,减肥,宴请,家常菜,小吃,炸,白领,私房菜,聚会",
                *   "material":[
                    1.  {
                        *   "mname":"生粉",
                        *   "type":0,
                        *   "amount":"适量"
                        },
                        {...}
                        {...}
                        ]
                     "process":[
                    1.  {
                         *   "pcontent":"首先我们将猪肉剁成肉泥、姜切成姜米、葱切葱花、蒜子切成蒜末、茄子去皮,然后在每一小段中间切一刀,但不要切断,做成茄盒。",
                     *       "pic":"http://123123/recipe/upload/20160719/162541_29953.jpg"
                        },
                        {[...]}
                        {[...]}
                        ]
                        }}}}

请问如何遍历出所有字段数据了并可以插入数据库中,我尝试了三个for循环遍历最后都是material[]、pcontent[]里面都是重复插入的值

    for x in data['result']['result']['list']:
        caipu_id = x['id']
        classid_id = x['classid']
        name = x['name']
        peoplenum = x['peoplenum']  # 人数
        preparetime = x['preparetime']  # 做菜时间
        content = x['content']  # 简介
        pic = x['pic']  # 背景图
        tag = x['tag']
        for a in x['material']:
            mname_null.append(a['mname'])
            amount_null.append(a['amount'])
            # mname_null.clear()   #清空list
        for (q,d) in zip(mname_null,amount_null):
            data_null.append(q)
            data_null.append(d)
        for i in x['process']:
            material_null.append(i['pcontent'])
            pic_null.append(i['pic'])
        for (g, k) in zip(material_null, pic_null):
            process_null.append(g)
            process_null.append(k)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
# -*- coding: utf-8 -*-
from pprint import pprint
import json

test_json = json.loads("""{
"problems": [{
    "Diabetes":[{
        "medications":[{
            "medicationsClasses":[{
                "className":[{
                    "associatedDrug":[{
                        "name":"asprin",
                        "dose":"",
                        "strength":"500 mg"
                    }]
                }]
            }]
        }],
        "labs":[{
            "missing_field": "missing_value"
        }]
    }],
    "Asthma":[{}]
}]}""")

fields_dict = {}


def recur_from_dict(dict_json):
    for key in dict_json:
        if type(value := dict_json.get(key)) not in (dict, list):
            fields_dict[key] = value
            # insert data into db here
        elif type(value) == dict:
            recur_from_dict(value)
        elif type(value) == list:
            for item in value:
                if type(item) == dict:
                    recur_from_dict(item)


recur_from_dict(dict_json=test_json)
pprint(fields_dict)

一个简单的递归,不过只能获取 key:value 格式的数据,对于 key: [value1, value2, value3]格式这种没有处理。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...