Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将json加载到dict并访问数据_Python_Json - Fatal编程技术网

在python中将json加载到dict并访问数据

在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

我有一个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 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'])