[英]how to convert a string into json in python?
當我這樣做時,我有一個從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"}
OP要求一些定制值,這些值不是刪除標簽字后剩下的確切值。 為此,我們必須逐行處理。
接受文本輸入並將其分成幾行:
>>> text = """commit 34343asdfasdf343434asdfasdfas
... Author: John Doe <john@doe.com>
... Date: Wed Jun 25 09:51:49 2014 +0800"""
...
>>> lines = text.split("\n")
>>> lines
['commit 34343asdfasdf343434asdfasdfas',
'Author: John Doe <john@doe.com>',
'Date: Wed Jun 25 09:51:49 2014 +0800']
假定行的固定順序並逐步進行處理:
>>> dct = {}
>>> dct["commit"] = lines[0].split()[1]
>>> dct["Author"] = lines[1].split(": ")[1].split(" <")[0]
>>> dct["Date"] = " ".join(lines[2].split(": ")[1].split()[:3])
創建最終字典:
>>> dct
{'Author': 'John Doe',
'Date': 'Wed Jun 25',
'commit': '34343asdfasdf343434asdfasdfas'}
可以轉儲為字符串:
>>> import json
>>> json.dumps(dct)
'{"Date": "Wed Jun 25", "commit": "34343asdfasdf343434asdfasdfas", "Author": "John Doe"}'
import subprocess
results = subproccess.Popen("git show xxxx | head -3",stdout=subprocess.PIPE,shell=True).communicate()[0].strip()
data = {}
for line in results.splitlines():
key,value = line.split(" ",1)
data[re.sub("[^a-zA-Z]","",key)] = value
json.dumps(data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.