我对Python很陌生,但我选择了一个实际上与工作相关的问题,我想当我弄清楚如何去做时,我会一路学习。
我有一个包含JSON格式文件的目录。我已经将目录中的所有内容导入到一个列表中,并遍历该列表来执行一个简单的打印,以验证我获得了数据。
我正试图找出如何在Python中实际使用给定的JSON对象。在javascript中
var x = {'asd':'bob'}
alert( x.asd ) //alerts 'bob'
访问对象的各种属性是简单的点表示法。Python的等价物是什么?
所以这是我的代码,正在进行导入。我想知道如何处理存储在列表中的各个对象。
#! /usr/local/bin/python2.6
import os, json
#define path to reports
reportspath = "reports/"
# Gets all json files and imports them
dir = os.listdir(reportspath)
jsonfiles = []
for fname in dir:
with open(reportspath + fname,'r') as f:
jsonfiles.append( json.load(f) )
for i in jsonfiles:
print i #prints the contents of each file stored in jsonfiles
当您
json.load
一个包含JSON形式的Javascript对象(如{'abc': 'def'}
)的文件是一个Python dictionary(通常被亲切地称为dict
)(在本例中恰好与Javascript对象具有相同的文本表示)。要访问特定的项,您可以使用索引,
mydict['abc']
,而在Javascript中,您可以使用属性访问符号,myobj.abc
。Python中的属性访问表示法是可以在dict上调用的方法,例如mydict.keys()
将给出['abc']
,一个包含字典中所有键值的列表(在本例中,只有一个键值,它是一个字符串)。字典的功能非常丰富,有大量的方法可以让您的头脑旋转,并且对许多Python语言结构有很强的支持(例如,您可以在dict上循环,
for k in mydict:
,并且k
将迭代和顺序地遍历字典的键)。若要访问所有属性,请在追加列表之前尝试eval()语句。
比如:
相关问题 更多 >
编程相关推荐