在python中从json文件加载数据的正确方法

在python中从json文件加载数据的正确方法,python,json,google-app-engine,Python,Json,Google App Engine,我正在尝试用python编写代码并部署到google app engine上。这两件事我都不熟悉。我有json,它包含以下内容 [ { "sentiment":-0.113568, "id":455908588913827840, "user":"ANI", "text":"Posters put up against Arvind Kejriwal in Varanasi http://t.co/ZDrzjm84je", "created_at":1

我正在尝试用python编写代码并部署到google app engine上。这两件事我都不熟悉。我有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:列表索引必须是整数,而不是str 如果我取消对打印数据行的注释并删除最后两行,我可以在控制台中看到所有数据。我想能够做一些计算的感情,也搜索一些文字中的文字。但为此,我需要知道如何一行一行地获得它。

试试这个:

import json

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

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

f.close()

for row in data:
        print row['sentiment']
试试这个:

import json

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

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

f.close()

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

如果你想清理一下的话

import json

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

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

“with”仅使文件在使用时保持打开状态,然后在执行下的缩进块后自动将其关闭。

如果您想稍微清理一下的话

import json

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

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

“with”仅使文件保持打开状态,然后在执行下的缩进块后自动关闭文件。

问题在于您使用的是
数据['emotation']
而不是
行['emotation']
,否则您的代码很好:

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
以open('data/convertsv.json','rb')作为文件的
:
data=simplejson.load(文件)
#打印数据
对于数据中的行:

打印行['emotional']#问题是您使用
数据['emotional']
而不是
行['emotional']
否则您的代码就可以了:

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
以open('data/convertsv.json','rb')作为文件的
:
data=simplejson.load(文件)
#打印数据
对于数据中的行:
打印行[“情绪”]#无需使用
.loads()
,。无需使用
.loads()