gpt4 book ai didi

python - 如何在python中将字符串转换为json?

转载 作者:太空宇宙 更新时间:2023-11-04 01:16:19 25 4
gpt4 key购买 nike

当我这样做时,我有一个从 git 得到的字符串

> git show xxxx | head -3

commit 34343asdfasdf343434asdfasdfas
Author: John Doe <john@doe.com>
Date: Wed Jun 25 09:51:49 2014 +0800

我需要使用 python 将打印到控制台的这个字符串转换为 json 格式,这样格式就是(我正在用脚本编写)

{'commit': '34343asdfasd343adfas', 'Author': 'john doe', 'date': 'wed jun 25'} 

目前我正在尝试手动拆分字符串中的第一个空格。

最佳答案

这适用于您的示例:

>>> txt='''\
... commit 34343asdfasdf343434asdfasdfas
... Author: John Doe <john@doe.com>
... Date: Wed Jun 25 09:51:49 2014 +0800'''
>>> json.dumps({k:v for k,v in re.findall(r'^([^\s]+)\s+(.+?)$', txt, re.M)})
{"commit": "34343asdfasdf343434asdfasdfas", "Date:": "Wed Jun 25 09:51:49 2014 +0800", "Author:": "John Doe <john@doe.com>"}

如果你有 git... 部分,把它分开:

>>> json.dumps({k:v for k,v in re.findall(r'^([^\s]+)\s+(.+?)$', 
txt.partition('\n\n')[2], re.M)})

如果你想放开 : 只需更改正则表达式捕获组即可:

>>> json.dumps({k:v for k,v in re.findall(r'^(\w+):?\s+(.+?)$', 
txt.partition('\n\n')[2], re.M)})
{"Date": "Wed Jun 25 09:51:49 2014 +0800", "commit": "34343asdfasdf343434asdfasdfas", "Author": "John Doe <john@doe.com>"}

如果您想丢失电子邮件地址:

>>> json.dumps({k:v for k,v in re.findall(r'^(\w+):?\s+(.+?)(?:\s*<[^>]*>)?$', 
txt.partition('\n\n')[2], re.M)})
{"Date": "Wed Jun 25 09:51:49 2014 +0800",
"commit": "34343asdfasdf343434asdfasdfas", "Author": "John Doe"}

关于python - 如何在python中将字符串转换为json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24441826/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com