在Python 2.6中处理JSON?
我刚开始学习Python,但我选择了一个跟工作有关的问题,我觉得在解决这个问题的过程中我能学到很多东西。
我有一个文件夹,里面全是格式为JSON的文件。我已经把这个文件夹里的所有文件导入到一个列表里,并且通过遍历这个列表,简单地打印出来,确认我得到了数据。
现在我想弄明白如何在Python中处理一个特定的JSON对象。在JavaScript中,这个过程非常简单:
var x = {'asd':'bob'}
alert( x.asd ) //alerts 'bob'
在JavaScript中,访问对象的各种属性只需要用点(.)来表示。那么在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
2 个回答
-1
要访问所有的属性,可以在添加列表之前尝试使用 eval() 语句。
比如:
import os
#define path to reports
reportspath = "reports/"
# Gets all json files and imports them
dir = os.listdir(reportspath)
for fname in dir:
json = eval(open(fname).read())
# now, json is a normal python object
print json
# list all properties...
print dir(json)
11
当你用 json.load
读取一个包含像 {'abc': 'def'}
这样的JavaScript对象的JSON格式的文件时,你得到的是一个Python中的 字典(通常我们亲切地称它为 dict
)。在这个例子中,它的文本表示和JavaScript对象是一样的。
如果你想访问字典中的某个特定项,可以使用索引,比如 mydict['abc']
。而在JavaScript中,你会用属性访问的方式,比如 myobj.abc
。在Python中,用属性访问的方式会得到一些可以在字典上调用的方法,比如 mydict.keys()
会返回 ['abc']
,这是一个包含字典中所有键的列表(在这个例子里,只有一个键,它是一个字符串)。
字典功能非常强大,有很多方法可以使用,让人眼花缭乱。此外,它还很好地支持许多Python的语言结构(例如,你可以对字典进行循环,使用 for k in mydict:
,这样 k
就会依次遍历字典的所有键)。