我有一个可以是以下两种形式之一的字符串:
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/