Python删除JSON子字符串

dev*_*vin 4 python string json

如果我有一个字符串,其中有一个有效的JSON子字符串,如下所示:

 mystr = '100{"1":2, "3":4}312'
Run Code Online (Sandbox Code Playgroud)

提取JSON字符串的最佳方法是什么?外面的数字可以是任何东西(a {或除外}),包括换行符和类似的东西.

需要明确的是,这是我想要的结果

  newStr = '{"1":2, "3":4}'
Run Code Online (Sandbox Code Playgroud)

我能想到做到这一点,最好的办法是使用find和rfind再取子.这对我来说似乎太冗长了,它不符合python 3.0(我更喜欢但不是必需的)

任何帮助表示赞赏.

Sco*_*t A 6

请注意,以下代码非常假定JSON字符串两侧除了非括号材料之外没有其他内容.

import re
matcher = re.compile(r"""
^[^\{]*          # Starting from the beginning of the string, match anything that isn't an opening bracket
       (         # Open a group to record what's next
        \{.+\}   # The JSON substring
       )         # close the group
 [^}]*$          # at the end of the string, anything that isn't a closing bracket
""", re.VERBOSE)

# Your example
print matcher.match('100{"1":2, "3":4}312').group(1)

# Example with embedded hashmap
print matcher.match('100{"1":{"a":"b", "c":"d"}, "3":4}312').group(1)
Run Code Online (Sandbox Code Playgroud)

简短的,未预编译的,未评论的版本:

import re
print re.match("^[^\{]*(\{[^\}]+\})[^}]*$", '100{"1":2, "3":4}312').group(1)
Run Code Online (Sandbox Code Playgroud)

虽然为了维护起见,但非常希望评论正则表达式.