簡體   English   中英

如何訪問彼此嵌套的多個字典和列表層並將它們收集到列表中

[英]how to access several layers of dictionaries and lists nested within each other and collect them into a list

我希望訪問此json文件中的圖像的URL。 但是我只能在巢中走得這么遠。 我得到的圖像打印出“url”:// images ....

{
    "devices": [
        {
            "variants": 
            [
                {
                    "iMEIPrefix": null,

                    {
                        "totalTax": 0,

                    },
                    "smartTab": {
                        "payOffPeriod": 24,
                        "requiredUpfrontPayment": 0,

                    },
                    "pricingForUi": {
                        "payOffPeriod": 24,
                        "requiredUpfrontPayment": 0,

                    },

                    "memory": "64GB",
                    "phoneImages": [
                        {
                            "url": "//images.ctfassets.net/7bx5buq4osbe/4tfPcjBNmnbWupJ7byONiZ/0f27dc736403c4027bbf13f184ffd4fc/PIXEL3A-BLACK-FRONT.png",
                            "title": "PIXEL3A-BLACK-FRONT",
                            "description": null
                        },
                        {
                            "url": "//images.ctfassets.net/7bx5buq4osbe/1UVKkXIBCUPkKJ8ROvFkOO/8f25b2c57bfd774792dfb69ed1d3cc29/PIXEL3A-BLACK-SIDE.png",
                            "title": "PIXEL3A-BLACK-SIDE",
                            "description": null
                        },
                        {
                            "url": "//images.ctfassets.net/7bx5buq4osbe/1K2AP67ZhWb9pBtIp3r1sj/755bdc263d4a6e43e8275bea2beb92d3/PIXEL3A-BLACK-BACK.png",
                            "title": "PIXEL3A-BLACK-BACK",
                            "description": null
                        }
                    ],

我的代碼到目前為止

phoneImages = phone['variants'][0]['phoneImages']

data['image'] = phoneImages

例如我希望有這個輸出:

"image": [                                      
    "https://xpressphone-backend.herokuapp.com/Apple iPhone XR/xr-black-front.png",
    "https://xpressphone-backend.herokuapp.com/Apple iPhone XR/xr-black-back.png"
],

它不是一個有效的json文件,你應該刪除{"totalTax": 0},這部分或轉換為"totalTax": 0

data = {}
phoneImages = [image['url'] for image in phone['devices'][0]['variants'][0]['phoneImages']]
data['image'] = phoneImages
print(data)

O / P:

{'image': ['//images.ctfassets.net/7bx5buq4osbe/4tfPcjBNmnbWupJ7byONiZ/0f27dc736403c4027bbf13f184ffd4fc/PIXEL3A-BLACK-FRONT.png', '//images.ctfassets.net/7bx5buq4osbe/1UVKkXIBCUPkKJ8ROvFkOO/8f25b2c57bfd774792dfb69ed1d3cc29/PIXEL3A-BLACK-SIDE.png', '//images.ctfassets.net/7bx5buq4osbe/1K2AP67ZhWb9pBtIp3r1sj/755bdc263d4a6e43e8275bea2beb92d3/PIXEL3A-BLACK-BACK.png']}
urls = []

phoneImages = phone['variants'][0]['phoneImages']

for phoneImage in phoneImages:
  urls.append = phoneImage['url']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM