python - 从字符串中解析有效的 JSON 对象或数组

标签 python regex python-3.x

我有一个可以是以下两种形式之一的字符串:

name multi word description {...}

name multi word description [...]

其中 {...}[...] 是任何有效的 JSON。我有兴趣只解析字符串的 JSON 部分,但我不确定最好的方法(特别是因为我不知道字符串将是两种形式中的哪一种)。这是我目前的方法:

import json

string = 'bob1: The ceo of the company {"salary": 100000}' 
o_ind = string.find('{')
a_ind = string.find('[')

if o_ind == -1 and a_ind == -1:
    print("Could not find JSON")
    exit(0)

index = min(o_ind, a_ind)
if index == -1:
    index = max(o_ind, a_ind)

json = json.loads(string[index:])
print(json)

它有效,但我忍不住觉得它可以做得更好。我想也许是正则表达式,但我在匹配子对象和数组而不是最外层的 json 对象或数组时遇到了麻烦。有什么建议吗?

最佳答案

您可以通过检查 {[ 的存在来定位 JSON 的开头,然后将字符串末尾的所有内容保存到捕获组中:

>>> import re
>>> string1 = 'bob1: The ceo of the company {"salary": 100000}'
>>> string2 = 'bob1: The ceo of the company ["10001", "10002"]'
>>> 
>>> re.search(r"\s([{\[].*?[}\]])$", string1).group(1)
'{"salary": 100000}'
>>> re.search(r"\s([{\[].*?[}\]])$", string2).group(1)
'["10001", "10002"]'

此处 \s([{\[].*?[}\]])$ 分解为:

  • \s - 单个空格字符
  • 括号是capturing group
  • [{\[] 将匹配单个 {[(后者需要用反斜杠转义)
  • .*? 是一个 non-greedy 匹配任何字符任意次数
  • [}\]] 将匹配单个 }](后者需要用反斜杠转义)
  • $表示字符串结束

或者,您可以使用 re.split()用空格分隔字符串,后跟 {[(向前看)并获取最后一项。它适用于您提供的示例输入,但不确定这在一般情况下是否可靠:

>>> re.split(r"\s(?=[{\[])", string1)[-1]
'{"salary": 100000}'
>>> re.split(r"\s(?=[{\[])", string2)[-1]
'["10001", "10002"]'

关于python - 从字符串中解析有效的 JSON 对象或数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34959948/

相关文章:

python - 识别具有相似地址的 ID

python-3.x - 使用 python3 和请求登录 Twitter

python - 迭代可能是迭代器或单个元素的东西

python - 如果 a == b 或 a == c : vs if a in {b, c}:

ruby-on-rails - Ruby 和 Null 字符的正则表达式匹配

linux - tkinter asksaveasfilename 不适用于文件扩展名中超过 1 个点

python - 循环更改 Pandas 数据框中列的顺序

python - 如何从JSON字符串中获取所需的内容

javascript - 如何使用正则表达式限制数字?

javascript - ^((?<!\/)\/[A-Za-z0-9_-]*)+$ 的正则表达式无效量词