如何从指定JSON数据中提取目标URL值
提取目标URL值的实现方法
先从JSON中获取body字段的文本内容,再通过正则匹配提取目标值,以下是几种常见实现方式:
Python 实现
import json import re # 原始JSON数据 raw_json = '''{ "attributes": {}, "body": "title: \\"store\\"\\n' + 'url: \\"https://fffffff.com/crr\\"\\n' + 'adsense: ", "bodyBegin": 1 }''' # 解析JSON并获取body内容 parsed_data = json.loads(raw_json) body_text = parsed_data["body"] # 正则匹配目标内容 target_pattern = r'url: "(.*?\\n)' match_result = re.search(target_pattern, body_text) if match_result: extracted_value = match_result.group(1) print(extracted_value) # 输出结果:https://fffffff.com/crr"\n
JavaScript 实现
// 原始JSON字符串 const rawJson = `{ "attributes": {}, "body": "title: \\"store\\"\\n' + 'url: \\"https://fffffff.com/crr\\"\\n' + 'adsense: ", "bodyBegin": 1 }`; // 解析JSON const data = JSON.parse(rawJson); const bodyText = data.body; // 正则匹配提取目标值 const regex = /url: "(.*?\\n)/; const match = bodyText.match(regex); if (match) { const extractedValue = match[1]; console.log(extractedValue); // 输出结果:https://fffffff.com/crr"\n }
正则表达式说明
使用的正则模式为 url: "(.*?\\n):
url: "匹配固定前缀,准确定位目标值的起始位置(.*?\\n)采用非贪婪匹配,捕获从起始位置到\n(转义后为\\n)的所有内容,即需要提取的目标值
内容的提问来源于stack exchange,提问作者Monsoon Malabar
相关产品推荐
相关产品推荐

