[英]How to parse an unquoted json string to a dict in python?
我有以下格式的字符串:
'{comm:comm123,date: Aug 29, 2019 12:30:00 PM,value:qwert}'
我想得到這樣的東西:
{
'comm': 'comm123',
'date': Aug 29, 2019 12:30:00 PM, (As a date)
'value': 'qwert'
}
我曾嘗試使用literal_eval 和eval,但它們沒有幫助。 我也嘗試使用 json 庫,但它似乎沒有任何用途。
您的字符串確實不明確,但是,您可以使用re.findall
:
import re
d = '{comm:comm123,date: Aug 29, 2019 12:30:00 PM,value:qwert}'
new_d = re.findall('[A-Z][a-z]{2}\s\d{2},\s\d{4}\s\d{2}:\d{2}:\d{2} [APM]{2}|\w+', d)
result = {new_d[i]:new_d[i+1] for i in range(0, len(new_d), 2)}
輸出:
{'comm': 'comm123', 'date': 'Aug 29, 2019 12:30:00 PM', 'value': 'qwert'}
可怕。 鍵似乎應該是明確的 - 如果你知道它們總是 alpha-only 可以使用類似([a-zA-Z]+):
東西提取它們,然后使用它來獲取字符串的“其他”位哪些必須是值?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.