在Python中从JSON文件加载数据的正确方法

0 投票
3 回答
2227 浏览
提问于 2025-04-18 05:17

我正在尝试用Python写代码,并把它部署到谷歌应用引擎上。我对这两者都很陌生。我有一个包含以下内容的json文件:

[
  {
    "sentiment":-0.113568,
    "id":455908588913827840,
    "user":"ANI",
    "text":"Posters put up against Arvind Kejriwal in Varanasi http://t.co/ZDrzjm84je",
    "created_at":1.397532052E9,
    "location":"India",
    "time_zone":"New Delhi"
  },
  {
    "sentiment":-0.467335,
    "id":456034840106643456,
    "user":"Kumar Amit",
    "text":"Arvind Kejriwal's interactive session with Varansi Supporter and Opponent will start in short while ..Join at http://t.co/f6xI0l2dWc",
    "created_at":1.397562153E9,
    "location":"New Delhi, Patna.",
    "time_zone":"New Delhi"
  },

我想在Python中加载这些数据。我有以下代码:

data = simplejson.load(open('data/convertcsv.json'))
        # print data
        for row in data:
            print data['sentiment']

但是我遇到了一个错误 - TypeError: list indices must be integers, not str(类型错误:列表索引必须是整数,而不是字符串)。如果我取消注释打印数据的那一行,并删除最后两行,我可以在控制台看到所有数据。我想对情感进行一些计算,并在文本中搜索一些词汇。但为此我需要知道如何逐行获取这些数据。

3 个回答

0

问题在于你用了 data['sentiment'],而应该用 row['sentiment']。其他的代码都没问题:

with open('data/convertcsv.json', 'rb') as file:
    data = simplejson.load(file)
# print data
for row in data:
    print row['sentiment'] # <-- data is a list, use `row` here
4

如果你想让代码看起来更整洁一些

import json

with open('data/convertcsv.json') as f:
    data = json.loads(f.read())

for row in data:
    print row['sentiment']

使用'with'这个写法可以让文件在使用的时候保持打开状态,等到下面的代码块执行完后,它会自动关闭文件。

1

试试这个:

import json

f = open('data/convertcsv.json');

data = json.loads(f.read())

f.close()

for row in data:
        print row['sentiment']

撰写回答