【发布时间】:2010-12-16 02:09:46
【问题描述】:
我对 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
【问题讨论】:
-
如果有人想在 Python 2.6 之前使用 JSON,我推荐
simplejson模块。官方的 JSON 支持改编自simplejson,所以它们应该非常相似。 code.google.com/p/simplejson