如何从无效JSON取值?从格式异常的JSON描述字段提取价格
解决两个JSON数据提取问题
1. 从无效JSON中提取目标值的方法
无效JSON(比如引号缺失、逗号错误、语法不严谨)确实挺闹心的,这里给你几个实用的解决思路:
正则表达式匹配(适合目标值格式固定的场景)
如果要提取的字段(比如price)有明显的格式规律,比如总是跟着"price":或者特定的标识文本,直接用正则抓效率很高。举个Python的例子:import re invalid_json_str = '{"status":"success", "response":{... "description":"Price: ₹399 ...", ...}}' # 匹配带货币符号的价格,这里以印度卢比为例 price_match = re.search(r'Price:\s*₹?(\d+)', invalid_json_str) if price_match: extracted_price = price_match.group(1) print(f"提取到价格:{extracted_price}")使用容错型JSON解析库
很多语言都有能兼容不规范JSON的库,比如Python的demjson或者json5,它们能自动修正部分语法错误(比如缺失的引号、 trailing逗号):import json5 invalid_json_str = '{"status":"success", response:{id:"67462", ...}}' # 缺少引号的不规范JSON try: data = json5.loads(invalid_json_str) target_value = data['response'].get('price') print(f"提取到目标值:{target_value}") except Exception as e: print(f"解析失败:{e}")
2. 从NYKAA接口不规范的description中提取price字段
针对你提供的NYKAA接口,外层JSON结构是规范的,先正常解析拿到description字段,再根据它的具体格式提取价格:
场景1:description是带价格的自然语言/HTML文本
import requests import re url = "https://www.nykaa.com/app-api/index.php/products/details?product_id=67462&sort=newest&source=react" response = requests.get(url) if response.status_code == 200: try: data = response.json() description = data['response'].get('description', '') # 匹配常见的价格格式,比如₹399、Rs. 399 price_pattern = re.compile(r'(?:₹|Rs\.)\s*(\d+)', re.IGNORECASE) price_match = price_pattern.search(description) if price_match: price = price_match.group(1) print(f"从description提取到价格:{price}") else: print("未在description中找到价格") except ValueError as e: print(f"外层JSON解析失败:{e}") else: print(f"请求接口失败,状态码:{response.status_code}")
场景2:description是不规范的JSON片段
如果description本身是个写坏的JSON对象(比如缺引号、语法错误),就用容错解析库处理:
import json5 # 假设description是这样的不规范片段:'{price:399, discount:"10%"}' description = data['response'].get('description', '') try: desc_data = json5.loads(description) price = desc_data.get('price') print(f"提取到价格:{price}") except Exception as e: print(f"解析description失败:{e}")
内容的提问来源于stack exchange,提问作者NigSys Technologies
相关产品推荐
相关产品推荐

