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
相关推荐
IamZJT_5 分钟前
拒绝做 AI 的“饲养员” ❌:前端程序员在 AI 时代的生存与进化指南 🚀
前端·ai编程
MM_MS9 分钟前
Halcon控制语句
java·大数据·前端·数据库·人工智能·算法·视觉检测
程序员Agions20 分钟前
程序员武学修炼手册(二):进阶篇——小有所成,从能跑就行到知其所以然
前端·程序员
清水白石00823 分钟前
深入 Python 的底层世界:从 C 扩展到 ctypes 与 Cython 的本质差异全解析
c语言·python·neo4j
小画家~24 分钟前
第四十六: channel 高级使用
java·前端·数据库
Amelia11111130 分钟前
day49
python
小贵子的博客34 分钟前
Ant Design Vue <a-table>
前端·javascript·vue.js·anti-design-vue
m0_5027249536 分钟前
vue动态设置背景图片后显示异常
前端·css
console.log('npc')43 分钟前
vue2中子组件父组件的修改参数
开发语言·前端·javascript
IT=>小脑虎1 小时前
2026版 Python零基础小白学习知识点【基础版详解】
开发语言·python·学习