简体   繁体   English

如何在python中将未加引号的json字符串解析为dict?

[英]How to parse an unquoted json string to a dict in python?

I have string in the format of:我有以下格式的字符串:

'{comm:comm123,date: Aug 29, 2019 12:30:00 PM,value:qwert}'

I want to get something like this:我想得到这样的东西:

{
   'comm': 'comm123',
   'date': Aug 29, 2019 12:30:00 PM,   (As a date)
   'value': 'qwert'
}

I have tried using literal_eval and eval but they do not help.我曾尝试使用literal_eval 和eval,但它们没有帮助。 i also tried using json library but it does not seem to serve any purpose.我也尝试使用 json 库,但它似乎没有任何用途。

Your string is indeed ambiguous, however, you can use re.findall :您的字符串确实不明确,但是,您可以使用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)}

Output:输出:

{'comm': 'comm123', 'date': 'Aug 29, 2019 12:30:00 PM', 'value': 'qwert'}

Horrible.可怕。 The keys seem like they should be unambiguous though - if you know they are always alpha-only could extract them using something like ([a-zA-Z]+): , then use that to get the "other" bits of the string which must be the values?键似乎应该是明确的 - 如果你知道它们总是 alpha-only 可以使用类似([a-zA-Z]+):东西提取它们,然后使用它来获取字符串的“其他”位哪些必须是值?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM