【问题标题】:Parse JSON String with regular expression in Python [closed]在 Python 中使用正则表达式解析 JSON 字符串 [关闭]
【发布时间】:2020-12-21 14:23:42
【问题描述】:

我有一个 JSON 字符串

json_str = '''
{"conversation_id": "314123790001", "first_agent_id": 85860001, "customer_id": 62483180001, "first_utterance_ts": "2020-08-18T15:37:04.826000+00:00", "first_utterance_text": "Wan indicator light", "first_intent_code": "TSMODEM", "first_intent_code_alt": "TSBOX", "final_intent_code": "TSWIFI", "intent_path": "TSMODEM,TSWIFI", "disambig_count": 0, "ftd_visit": true, "faq_id": null, "final_action_destination": null, "is_first_intent_correct": null, "issue_id": "314123790001", "first_rep_id": 85860001, "company_name": "spectrum-cable"}
'''

我使用了这个正则表达式命令;

_key = "intent_path"
values = re.findall(r'\"{}\"\s?:\s?\"?([^\,\"]+)\"?'.format(_key), json_str)

但是,我得到了一个结果“TSMODEM”。我的预期结果是“TSMODEM,TSWIFI”

我只想获得一个键的值(“intent_path”)。我想用正则表达式获取值。你能帮帮我吗?

【问题讨论】:

  • 为什么使用正则表达式(对于结构化数据来说是个糟糕的选择)?你想解析所有字段还是只提取一个值?
  • "带有正则表达式,但不是 json python 库" - 你能详细说明原因吗?另外,你自己有没有尝试过?
  • 你能解释一下为什么你不想使用 JSON 库吗?这是字面上他们唯一的目的。
  • 因为我经常得到一个损坏的JSON字符串,所以我想使用正则表达式。
  • 如果您经常收到损坏的 JSON,则正则表达式也可能会损坏。修复任何给你 JSON 的东西,或者如果它的第三方报告错误

标签: python json regex


【解决方案1】:

试试下面的正则表达式:

intent_path":\s*"((?:(?!(?<!\\)").)*)"

Regex Demo

  1. "intent_path":\s*" 匹配“intent_path”:后跟 0 个或多个空格字符,后跟一个“。
  2. ((?:(?!(?&lt;!\\)").)*) 匹配 0 个或多个字符,只要它不是前面没有反斜杠的 " 字符。这些字符在捕获组 1 中累积。
  3. " 匹配一个 " 字符

代码:

import re

json_str = '''
{"conversation_id": "314123790001", "first_agent_id": 85860001, "customer_id": 62483180001, "first_utterance_ts": "2020-08-18T15:37:04.826000+00:00", "first_utterance_text": "Wan indicator light", "first_intent_code": "TSMODEM", "first_intent_code_alt": "TSBOX", "final_intent_code": "TSWIFI", "intent_path": "TSMODEM,TSWIFI", "disambig_count": 0, "ftd_visit": true, "faq_id": null, "final_action_destination": null, "is_first_intent_correct": null, "issue_id": "314123790001", "first_rep_id": 85860001, "company_name": "spectrum-cable"}
'''

_key = "intent_path"
m = re.search(fr'"{re.escape(_key)}":\s*"((?:(?!(?<!\\)").)*)"', json_str)
if m:
    print(m[1])

打印:

TSMODEM,TSWIFI

【讨论】:

    【解决方案2】:

    我想出了这个正则表达式,它可能在大多数情况下都有效,但不是全部。既然你说你可能已经破坏了正则表达式,所以很难知道输出会是什么样子。无论如何,这可能适合您的需求。

    r'"intent_path":(?: ?)"([\w\s,]+)"'
    

    您可以测试更多案例here

    【讨论】:

    • @Adirio 哦,确实如此。比不错。感谢您指出这一点。
    猜你喜欢
    • 2015-11-22
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多