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
相关推荐
带娃的IT创业者8 分钟前
《Python实战进阶》专栏 No.3:Django 项目结构解析与入门DEMO
数据库·python·django
m0_5287238122 分钟前
HTML中,title和h1标签的区别是什么?
前端·html
Dark_programmer23 分钟前
html - - - - - modal弹窗出现时,页面怎么能限制滚动
前端·html
GDAL28 分钟前
HTML Canvas clip 深入全面讲解
前端·javascript·canvas
禾苗种树29 分钟前
在 Vue 3 中使用 ECharts 制作多 Y 轴折线图时,若希望 **Y 轴颜色自动匹配折线颜色**且无需手动干预,可以通过以下步骤实现:
前端·vue.js·echarts
HealthScience37 分钟前
【异常错误】pycharm debug view变量的时候显示不全,中间会以...显示
ide·python·pycharm
贵州数擎科技有限公司1 小时前
使用 Three.js 实现流光特效
前端·webgl
JustHappy1 小时前
「我们一起做组件库🌻」做个面包屑🥖,Vue的依赖注入实战💉(VersakitUI开发实录)
前端·javascript·github
拉不动的猪1 小时前
刷刷题16
前端·javascript·面试
豌豆花下猫2 小时前
Python 潮流周刊#90:uv 一周岁了,优缺点分析(摘要)
后端·python·ai