在Python 2.6中使用JSON?

2024-09-30 08:29:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我对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

Tags: 对象in目录json列表forosdir
2条回答

当您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()语句。

比如:

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)

相关问题 更多 >

    热门问题