我有一个字符串:
'{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'
并且希望将其转换为
{
"tomatoes" : "5" ,
"livestock" :"{"cow" : "5" , "sheep" :"2" }"
}
有什么想法吗?
我有一个字符串:
'{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'
并且希望将其转换为
{
"tomatoes" : "5" ,
"livestock" :"{"cow" : "5" , "sheep" :"2" }"
}
有什么想法吗?
这个问题在988251中已经解决。
简而言之,使用Python的ast
库的literal_eval()
函数即可。
import ast
my_string = "{'key':'val','key2':2}"
my_dict = ast.literal_eval(my_string)
source = '{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'
output = ""
quoting = False
for char in source:
if char.isalnum():
if not quoting:
output += '"'
quoting = True
elif quoting:
output += '"'
quoting = False
output += char
print(output) # {"tomatoes" : "5" , "livestock" :{"cow" : "5" , "sheep" :"2" }}
这样可以得到一个有效的JSON,现在您可以使用json
模块将其轻松解析为Python dict
:
import json
parsed = json.loads(output)
# {'livestock': {'sheep': '2', 'cow': '5'}, 'tomatoes': '5'}
parsed = eval(output)
? - innisfreeeval
,即使是疯子也应该三思而后行...如果真的找不到其他方法,那么请使用ast.literal_eval()
。此外,它比json.loads()
慢得多。 - zwer'{tomatoes: 5, livestock: {cow: 5, sheep: 2}}'
。 - innisfreeeval()
接触任意字符串(这就是为什么大多数人都想使用eval()
)。 - zwerimport json
with open("your file", "r") as f:
dictionary = json.loads(f.read());
现在字典包含了你正在寻找的数据结构。
这是我的答案:
dict_str = '{tomatoes: 5, livestock: {cow: 5, sheep: 2}}'
def dict_from_str(dict_str):
while True:
try:
dict_ = eval(dict_str)
except NameError as e:
key = e.message.split("'")[1]
dict_str = dict_str.replace(key, "'{}'".format(key))
else:
return dict_
print dict_from_str(dict_str)
eval
将字典str
转换为dict
。但是,我首先必须处理您的字典键没有用引号括起来的事实。我通过尝试评估它并捕获错误来解决这个问题。从错误消息中,我提取被解释为未知变量的键,并用引号括起来。
dict
一样。 这非常有趣,我想找出它的运作方式... JSON 是一种有用的方法,但是采用蛮力硬编码的方式如何? - drewteriyaki