如何从JSON数据中匹配title字段提取目标条目的id等指定字段值
筛选JSON字段提取ID的实现方案
需求说明
匹配JSON中的title字段值为6,同时option1/option2/option3字段取值为6的条目,提取对应条目的id值。
实现方式
1. Python实现
import json # 原始数据处理(去掉示例外层的括号,包装为合法JSON数组) raw_json_str = ''' { "id": 39430269435981, "title": "5.5", "option1": "5.5", "option2": null, "option3": null, "sku": "195241242248", "requires_shipping": true, "taxable": true, "featured_image": null, "available": false, "name": "Nike Dunk High 1985 - Lemon Drop / Black / Saturn Gold - 5.5", "public_title": "5.5", "options": ["5.5"], "price": 13108, "weight": 1361, "compare_at_price": null, "inventory_management": "shopify", "barcode": null }, { "id": 39430269468749, "title": "6", "option1": "6", "option2": null, "option3": null, "sku": "195241242255", "requires_shipping": true, "taxable": true, "featured_image": null, "available": false, "name": "Nike Dunk High 1985 - Lemon Drop / Black / Saturn Gold - 6", "public_title": "6", "options": ["6"], "price": 13108, "weight": 1361, "compare_at_price": null, "inventory_management": "shopify", "barcode": null } ''' # 转换为可解析的JSON数组 data_list = json.loads(f'[{raw_json_str}]') # 筛选符合条件的id result_ids = [] for item in data_list: # 判断条件:title为6,且option1/2/3任一值为6 if item.get('title') == '6' and (item.get('option1') == '6' or item.get('option2') == '6' or item.get('option3') == '6'): result_ids.append(item['id']) print(result_ids) # 运行输出:[39430269468749]
2. 命令行jq工具实现
先将原始数据整理为合法JSON数组保存为data.json,执行以下命令即可直接输出结果:
jq '.[] | select(.title == "6" and (.option1 == "6" or .option2 == "6" or .option3 == "6")) | .id' data.json
输出结果为:39430269468749
内容的提问来源于stack exchange,提问作者Marc9s
相关产品推荐
相关产品推荐

