JSON:
{
"Herausgeber": "Xema",
"Nummer": "1234-5678-9012-3456",
"Deckung": 2e+6,
"Waehrung": "EURO",
"Inhaber": {
"Name": "Mustermann",
"Vorname": "Max",
"maennlich": true,
"Hobbys": [ "Reiten", "Golfen", "Lesen" ],
"Alter": 42,
"Kinder": [],
"Partner": null
}
}
有没有一种快速的方法可以像在javascript中那样评估它,所以你可以通过简单地评估JSON格式的全文本文件来获得python 2.7对象?
所以你有类似的东西:
file = read('text.json')
obj = eval(file)
答案 0 :(得分:4)
不要eval()
;即使它们看起来很相似,JSON也不是Python。使用json
module解析它:
import json
with open('text.json') as f:
obj = json.load(f)
这使用json.load()
从打开的文件对象加载JSON数据。如果您有一个包含JSON数据的字符串,请使用json.loads()
(请注意s
)。
答案 1 :(得分:0)
您可以尝试:
eval("""{
"Herausgeber": "Xema",
"Nummer": "1234-5678-9012-3456",
"Deckung": 2e+6,
"Waehrung": "EURO",
"Inhaber": {
"Name": "Mustermann",
"Vorname": "Max",
"maennlich": true,
"Hobbys": [ "Reiten", "Golfen", "Lesen" ],
"Alter": 42,
"Kinder": [],
"Partner": null
}
}""")
上面的代码引发了一个错误:
NameError:name' true'未定义
因此,因为python中不接受true关键字,所以最好不要这样做。
import json
obj = json.loads("""{
"Herausgeber": "Xema",
"Nummer": "1234-5678-9012-3456",
"Deckung": 2e+6,
"Waehrung": "EURO",
"Inhaber": {
"Name": "Mustermann",
"Vorname": "Max",
"maennlich": true,
"Hobbys": [ "Reiten", "Golfen", "Lesen" ],
"Alter": 42,
"Kinder": [],
"Partner": null
}
}""")
print(obj)