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
相关推荐
Lynnxiaowen8 小时前
今天我们开始学习python3编程之python基础
linux·运维·python·学习
青青草原羊村懒大王8 小时前
1、pycharm相关知识
python
嫂子的姐夫8 小时前
10-七麦js扣代码
前端·javascript·爬虫·python·node.js·网络爬虫
Komorebi_99998 小时前
Vue3 + TypeScript provide/inject 小白学习笔记
前端·javascript·vue.js
少吃一口都不行8 小时前
脚手架学习
前端·javascript·学习
地方地方8 小时前
手写JavaScript 深拷贝
前端·javascript
yeyuningzi8 小时前
npm升级提示error engine not compatible with your version of node/npm: npm@11.6.2
前端·npm·node.js
1024小神8 小时前
next 项目中的 'use client' 是什么意思
前端
77qqqiqi8 小时前
python循环语句
python
我是华为OD~HR~栗栗呀9 小时前
24届-Python面经(华为OD)
java·前端·c++·python·华为od·华为·面试