Python提取字符串中的json,时间,特定字符

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
相关推荐
无名客022 分钟前
npm run dev 启动项目 报Error: listen EACCES: permission denied 0.0.0.0:80 解决方法
前端·javascript·vue.js
零点七九23 分钟前
vue npm install卡住没反应
前端·vue.js·npm
墨菲安全28 分钟前
NPM组件 @0xme5war/apicli 等窃取主机敏感信息
前端·npm·node.js·主机信息窃取·npm恶意包·npm投毒
Komorebi_999928 分钟前
vue create 项目名 和 npm init vue@latest 创建vue项目的不同
前端·vue.js·npm
W.KN2 小时前
PyTorch 数据类型和使用
人工智能·pytorch·python
虾饺爱下棋2 小时前
FCN语义分割算法原理与实战
人工智能·python·神经网络·算法
千册3 小时前
python+pyside6+sqlite 数据库测试
数据库·python·sqlite
好好研究3 小时前
使用JavaScript实现轮播图的自动切换和左右箭头切换效果
开发语言·前端·javascript·css·html
悠哉悠哉愿意6 小时前
【电赛学习笔记】MaixCAM 的OCR图片文字识别
笔记·python·嵌入式硬件·学习·视觉检测·ocr
nbsaas-boot6 小时前
SQL Server 窗口函数全指南(函数用法与场景)
开发语言·数据库·python·sql·sql server