这是我迄今为止的代码:
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
语句中使用哪个变量
如果有人能帮我,指导我打印所有的id,那将是太棒了。
for product in reqJson['product']['title']:
ProductTitle = product['title']
print (title)
我从您提供的链接中看到,列表中唯一的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']
。