Skip to main content
 首页 » 编程设计

python之从 JSON 文件加载数据

2025年05月04日7tintown

我正在尝试从 JSON 文件中获取一些数据。这是它的代码 -

import csv 
import json 
ifile  = open('facebook.csv', "rb") 
reader = csv.reader(ifile) 
 
rownum = 0 
for row in reader: 
    try: 
        csvfile = open('facebook.csv', 'r') 
        jsonfile = open('file.json', 'r+') 
        fieldnames = ("USState","NOFU2008","NOFU2009","NOFU2010", "12MI%", "24MI%") 
        reader = csv.DictReader( csvfile, fieldnames) 
        for row in reader: 
            json.dump(row, jsonfile) 
            jsonfile.write('\n') 
        data = json.load(jsonfile) 
        print data["USState"] 
    except ValueError: 
        continue 

我没有在打印语句的控制台上得到任何输出。 JSON格式如下

{"USState": "US State", "12MI%": "12 month increase %", "24MI%": "24 month increase %", "NOFU2010": "Number of Facebook UsersJuly 2010", "NOFU2008": "Number of Facebook usersJuly 2008", "NOFU2009": "Number of Facebook UsersJuly 2009"} 
{"USState": "Alabama", "12MI%": "109.3%", "24MI%": "400.7%", "NOFU2010": "1,452,300", "NOFU2008": "290,060", "NOFU2009": "694,020"} 

我想像 NOFU2008 一样访问所有行。

请您参考如下方法:

问题在于您创建 JSON 文件的方式。您不想对每一行使用 json.dump() 然后将它们附加到 JSON 文件。

要创建一个 JSON 文件,您应该首先在 Python 中创建一个数据结构,以您想要的方式表示整个文件,然后调用 json.dump() 一次只转储出来整个结构为 JSON 格式。

对整个文件进行一次 json.dump() 调用将确保它是有效的 JSON。

我还建议将您的列表/行数组包装在字典/对象中,这样您就有地方放置与整个 JSON 文件相关的其他属性,而不是单个行。

看起来你的 facebook.csv 的前几行是这样的(带或不带引号):

"US State","12 month increase %","24 month increase %","Number of Facebook UsersJuly 2010","Number of Facebook usersJuly 2008","Number of Facebook UsersJuly 2009" 
"Alabama","109.3%","400.7%","1,452,300","290,060","694,020" 

假设我们想从中生成这个 JSON 文件(为清楚起见,此处缩进):

{ 
    "rows": [ 
        { 
            "USState": "US State", 
            "12MI%": "Number of Facebook usersJuly 2008", 
            "24MI%": "Number of Facebook UsersJuly 2009", 
            "NOFU2010": "Number of Facebook UsersJuly 2010", 
            "NOFU2008": "12 month increase %", 
            "NOFU2009": "24 month increase %" 
        }, 
        { 
            "USState": "Alabama", 
            "12MI%": "290,060", 
            "24MI%": "694,020", 
            "NOFU2010": "1,452,300", 
            "NOFU2008": "109.3%", 
            "NOFU2009": "400.7%" 
        } 
    ] 
} 

请注意,JSON 文件的顶层是一个对象(不是数组),该对象有一个 rows 属性,它是行数组。

我们可以创建此 JSON 文件并使用此 Python 代码对其进行测试:

import csv 
import json 
 
# Read the CSV file and convert it to a list of dicts 
with open( 'facebook.csv', 'rb' ) as csvfile: 
    fieldnames = ( 
        "USState", "NOFU2008", "NOFU2009", "NOFU2010", 
        "12MI%", "24MI%" 
    ) 
    reader = csv.DictReader( csvfile, fieldnames ) 
    rows = list( reader ) 
 
# Wrap the list inside an outer dict 
wrap = { 
    'rows': rows 
} 
 
# Format and write the entire JSON in one fell swoop 
with open( 'file.json', 'wb' ) as jsonfile: 
    json.dump( wrap, jsonfile ) 
 
# Now test the file by reading it and parsing it 
with open( 'file.json', 'rb' ) as jsonfile: 
    data = json.load( jsonfile ) 
 
# For fun, convert the data back to JSON again and pretty-print it 
print json.dumps( data, indent=4 ) 

一些注意事项...此代码没有原始代码中的嵌套阅读器循环。我不知道那些是干什么用的。一位读者就足够了。

事实上,这个版本根本没有使用循环。此行从读取器对象生成行列表:

    rows = list( reader ) 

还要密切注意在打开 CSV 和 JSON 文件的地方使用 with。这是打开文件的好方法,因为文件将在 with block 的末尾自动关闭。

说了这么多,我想知道这个 JSON 结构是否是您真正想要的?看起来 CSV 的第一行是标题行,所以您可能想跳过该行?在将其余 CSV 数据转换为列表之前,您可以通过添加一个 reader.next() 调用来轻松做到这一点:

reader.next() 
    rows = list( reader ) 

此外,我不确定我是否了解您希望如何访问结果数据。您将无法使用 data["USState"],因为 USState 是每个单独行对象的属性。因此,请多说一些您希望如何访问数据,我们可以解决。