如何通过python访问json站点的某些值

2024-04-26 21:44:35 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我目前掌握的代码:

import json
import requests
import time

endpoint = "https://www.deadstock.ca/collections/new-arrivals/products/nike- 
air-max-1-cool-grey.json"
req = requests.get(endpoint)
reqJson = json.loads(req.text)

for id in reqJson['product']:
    name = (id['title'])
    print (name)

请随意访问该链接,我正在尝试获取所有"id"值并将其打印出来。以后会用它们来打发我的不和。你知道吗

我尝试了上面的代码,但我不知道如何获得这些值。我不知道在for in reqjson语句中使用哪个变量

如果有人能帮我,指导我把所有的身份证都打印出来,那就太棒了。你知道吗

for product in reqJson['product']['title']:
    ProductTitle = product['title']
    print (title)

Tags: 代码nameinimportidjsonfortime
1条回答
网友
1楼 · 发布于 2024-04-26 21:44:35

我从您提供的链接中看到,列表中仅有的id实际上是product下的variants列表的一部分。所有其他的id都不是列表的一部分,因此不需要迭代。为清晰起见,以下是数据摘录:

{
    "product":{
        "id":232418213909,
        "title":"Nike Air Max 1 \/ Cool Grey",
        ...
        "variants":[
            {
                "id":3136193822741,
                "product_id":232418213909,
                "title":"8",
                ...
            },
            {
                "id":3136193855509,
                "product_id":232418213909,
                "title":"8.5",
                ...
            },
            {
                "id":3136193789973,
                "product_id":232418213909,
                "title":"9",
                ...
            },
            ...
       ],
        "image":{
            "id":3773678190677,
            "product_id":232418213909,
            "position":1,
            ...
        }
    }
}

因此,您需要做的应该是遍历product下的variants列表:

import json
import requests

endpoint = "https://www.deadstock.ca/collections/new-arrivals/products/nike-air-max-1-cool-grey.json"
req = requests.get(endpoint)
reqJson = json.loads(req.text)

for product in reqJson['product']['variants']:
    print(product['id'], product['title'])

这将输出:

3136193822741 8
3136193855509 8.5
3136193789973 9
3136193757205 9.5
3136193724437 10
3136193691669 10.5
3136193658901 11
3136193626133 12
3136193593365 13

如果您只需要产品id和产品名称,它们将分别是reqJson['product']['id']reqJson['product']['title']。你知道吗

相关问题 更多 >