1.整个字符串为json
python
s='{"time":"2014-10-14 12:00", "tid":12, "info_message":"我爱python"}'
_json=json.loads(s)
print(_json)
执行结果:
{'time': '2014-10-14 12:00', 'tid': 12, 'info_message': '我爱python'}
2.字符串中包含其他字符
python
s="""2024-12-13 09:04:56,635 INFO [TID: da04c57a76e0467183b36e51ea0ceecd.105.17340806966210311] [http-nio-2020-exec-128] [mf-mobile-gateway] com.mf.mobile.gateway.filter.PostFilter:63 --- {"type":"response","origin":"7de37c362ee54dcf9c4561812309347a:1635104607816384512","url":"/api/oauth/token-verify?timestamp=1734080696621","responseBody":{"msg":"OK","code":0,"timeConsuming":8}
"""
time_pattern = r'(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})'
time_match = re.search(time_pattern, s)
time = time_match.group(1) if time_match else None
print(f"Time: {time}")
# 提取 TID
tid_pattern = r'TID: ([\w\.\d]+)'
tid_match = re.search(tid_pattern, s)
tid = tid_match.group(1) if tid_match else None
print(f"TID: {tid}")
# 提取字典内容
dict_str=re.search('({.+})', s).group(0)
print(dict_str)
_json=json.loads(s) print(_json)
2.2.字符串中包含其他字符,切json中包含转义及""
python
s="""2024-12-13 09:04:56,635 INFO [TID: da04c57a76e0467183b36e51ea0ceecd.105.17340806966210311] [http-exec-128] [mobile-gateway] com.mobile.gateway.filter.PostFilter:63 --- {"type":"response","origin":"7de37c362ee54dcf9c4561812309347a:1635104607816384512","url":"/api/oauth/token-verify?timestamp=1734080696621","responseBody":{"msg":"OK","code":0,"data":"{\"userid\":1635104607816384512,\"username\":\"123\"}"},"timeConsuming":8}
"""
# 提取字典内容
dict_str=re.search('({.+})', s).group(0)
print(dict_str)
data_str = dict_str.replace('"{', '{')
data_str = data_str.replace('}"', '}')
data = json.loads(data_str)
print(data['type'])
运行结果:
python
{"type":"response","origin":"7de37c362ee54dcf9c4561812309347a:1635104607816384512","url":"/api/oauth/token-verify?timestamp=1734080696621","responseBody":{"msg":"OK","code":0,"data":"{"userid":1635104607816384512,"username":"123"}"},"timeConsuming":8}
response