【发布时间】:2020-11-10 02:33:06
【问题描述】:
我正在尝试拆分一个字符串并获取其中的所有 json 字符串
我的字符串:
{"datas": {"type": "custom", "value": {"cat": "game", "func": "game", "args": ["action", "move" , "ball", 0, 55, 223]}}}{"datas": {"type": "auth", "value": 0}}{"datas": {"type": "custom", " value": {"cat": "game", "func": "game", "args": ["action", "move", "ball", 0, 60, 218]}}}{"datas" : {"type": "custom", "value": {"cat": "game", "func": "game", "args": ["action", "move", "ball", 0, 65, 213]}}}{"datas": {"type": "custom", "value": {"cat": "game", "func": "game", "args": ["action" , "移动", "球", 0, 70, 208]}}}
我的正则表达式:
({.*})({.*)
但是,第一组是没有最后一个json字符串的整个字符串
{"datas": {"type": "custom", "value": {"cat": "game", "func": "game", "args": ["action", "move" , "ball", 0, 55, 223]}}}{"datas": {"type": "auth", "value": 0}}{"datas": {"type": "custom", " value": {"cat": "game", "func": "game", "args": ["action", "move", "ball", 0, 60, 218]}}}{"datas" : {"type": "custom", "value": {"cat": "game", "func": "game", "args": ["action", "move", "ball", 0, 65, 213]}}}
我想像这样一个一个得到:
{"datas": {"type": "custom", "value": {"cat": "game", "func": "game", "args": ["action", "move" , "球", 0, 55, 223]}}}
我不知道如何正确解释我的问题,希望你能理解
感谢阅读
**编辑**:最后,我没有使用正则表达式。 这是我的功能:
def packet_to_jsonlist(s):
jsonlist = []
count = 0
current = 0
for i in range(0, len(s)):
if s[i] == '{':
count += 1
elif s[i] == '}':
count -= 1
if count == 0:
jsonlist.append(s[current:i+1])
current = i + 1
return jsonlist
【问题讨论】:
-
不要尝试处理 JSON 字符串。使用
json.loads(...)将其解析为dict并使用普通的dict/list 操作。 -
@Selcuk 这不是一个单一的字典。
-
...或者我应该说,不是单个 json 字符串。
-
@MarkMeyer 哦,对。格式并不明显。我想最好的方法是尽可能修复源。
标签: python python-3.x regex regex-group