用Python中的正则表达式解析JSON字符串

2024-10-01 17:37:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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\u path”)。我想用正则表达式得到这个值。你能帮我吗


Tags: pathkey字符串idjsoncodenullfinal
2条回答

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

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

您可以测试更多案例here

请尝试以下正则表达式:

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

Regex Demo

  1. "intent_path":\s*"匹配“intent_path”:后跟0个或多个空格字符,后跟“a”
  2. ((?:(?!(?<!\\)").)*)匹配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

相关问题 更多 >

    热门问题