You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何过滤JSON数据:根据指定name值获取对应id值

How to Retrieve the Corresponding ID from JSON by Specifying the 'name' Value

Hey there! You're already halfway there with your requests code—great job. Now let's turn that raw JSON text into something we can work with and pull out the ID you need. Here's how to do it step by step:

Step 1: Parse the JSON Response

First, we need to convert the JSON string returned by r.text into a Python dictionary (and nested list) that we can iterate through. We'll use Python's built-in json module for this.

Step 2: Find the Matching Entry

Next, we'll loop through the available_sizes list in the parsed data, check each entry's name value, and grab the corresponding id when we find a match.

Here's the full, updated code:

import requests
import json

s = requests.Session()
r = s.get('https://www.off---white.com/en/GB/men/products/omia066s188000161001.json')

# Convert JSON string to Python dictionary
product_data = json.loads(r.text)

# Define the name you want to look up
target_name = "40"

# Search for the matching size entry
for size_entry in product_data['available_sizes']:
    if size_entry['name'] == target_name:
        print(f"ID for size {target_name}: {size_entry['id']}")
        break  # Exit loop once we find our match
else:
    # Runs if no match was found in the loop
    print(f"Couldn't find an entry with name '{target_name}'")

Alternative: Concise One-Liner Approach

If you prefer a more compact solution, you can use a generator expression with next() to get the first matching ID directly:

import requests
import json

s = requests.Session()
r = s.get('https://www.off---white.com/en/GB/men/products/omia066s188000161001.json')
product_data = json.loads(r.text)

target_name = "40"
matching_id = next((entry['id'] for entry in product_data['available_sizes'] if entry['name'] == target_name), None)

if matching_id:
    print(f"ID for size {target_name}: {matching_id}")
else:
    print(f"No entry found for size {target_name}")

Both approaches will work—pick whichever makes more sense for your use case. The first is more explicit (great for readability), while the second is shorter if you're comfortable with generator expressions.

内容的提问来源于stack exchange,提问作者Piers Thomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:13:21