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

时间:2014-08-02 15:30:36

标签: 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 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
我做错了什么?这一直在阻止我。

第一个回答后: 谢谢!我添加了你的句子并且它有效(但我不明白为什么确切):

脚本现在是

import json
with open('data.json') as data_file:
    data = json.load(data_file)
trees = data['trees']
for keys,values in trees.items():
    print(keys)
    print(values)
print "yoyo"
print ("ulink of tree2 is %s" % trees['tree2']['ul'])

现在没有更多错误:

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字符都是为了回答键,在trees.irmes中的值....

  • 为什么我不能做

    trees = json.load(data_file)

代替

data = json.load(data_file)
trees = data['trees']

但它的表现,谢谢!

1 个答案:

答案 0 :(得分:2)

您调用了变量data,而不是treestreesdata字典中的关键字;也许你想用这个字典创建一个新的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'])