在python中将json加载到dict并访问数据
我有一个JSON文件,其中包含两棵树的数据,我想在脚本中使用:在python中将json加载到dict并访问数据,python,json,Python,Json,我有一个JSON文件,其中包含两棵树的数据,我想在脚本中使用: {"trees":{ "tree1":{"name":"tree1","tt1":"1","ul":"2"}, "tree2":{"name":"tree2","tt2":"1","ul":"2"} } } 我试试这个 import json with open('data.json') as data_file: data = json.load(data_file) print ("ulink of tree
{"trees":{
"tree1":{"name":"tree1","tt1":"1","ul":"2"},
"tree2":{"name":"tree2","tt2":"1","ul":"2"}
} }
我试试这个
import json
with open('data.json') as data_file:
data = json.load(data_file)
print ("ulink of tree2 is %s" % trees['tree2']['ul'])
但它说:
Traceback (most recent call last):
File "open-json.py", line 10, in <module>
print ("ulink of tree2 is %s" % trees['tree2']['ul'])
NameError: name 'trees' is not defined
现在不再出现错误:
tree1
{u'ul': u'2', u'tt1': u'1'}
tree2
{u'tt2': u'1', u'ul': u'2'}
yoyo
ulink of tree2 is 2
简化了json,顺便说一下
{"trees":{
"tree1":{"tt1":"1","ul":"2"},
"tree2":{"tt2":"1","ul":"2"}
} }
我不明白的是
- 为什么答案中的所有u字符都表示关键字、树中的值。irmes
- 为什么我不能这么做 trees=json.load(数据文件)
data = json.load(data_file)
trees = data['trees']
但这很重要,谢谢 您调用了变量
数据
,而不是树
<代码>树是数据
字典中的一个键;也许您想用该字典创建一个新的树
变量
with open('data.json') as data_file:
data = json.load(data_file)
trees = data['trees']
print ("ulink of tree2 is %s" % trees['tree2']['ul'])
树不应该是数组吗?另外,阅读您的错误。这是一个很好的解释,但如果不是,只需使用query=name of error进行搜索。
with open('data.json') as data_file:
data = json.load(data_file)
trees = data['trees']
print ("ulink of tree2 is %s" % trees['tree2']['ul'])