user3309069
user3309069

Reputation: 101

Right way to load data from json file in python

I am trying to write a code in python and deploy on google app engine. I am new to both these things. I have json which contains the following

[
  {
    "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"
  },

I am trying to load this data in python. I have the following code for it

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

I am getting the following error - TypeError: list indices must be integers, not str If I uncomment the print data line and remove the last 2 lines I can see all the data in console. I want to be able to do some computations on the sentiment and also search for some words in the text. But for that I need to know how to get it line by line.

Upvotes: 0

Views: 2245

Answers (3)

jfs
jfs

Reputation: 414875

The issue is that you use data['sentiment'] instead of row['sentiment'] otherwise your code is fine:

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

Upvotes: 0

MikeRixWolfe
MikeRixWolfe

Reputation: 430

If you'd like to clean it up a bit

import json

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

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

The 'with' only leaves the file open as its used, then closes it automatically once the indented block under is executed.

Upvotes: 4

pah
pah

Reputation: 4778

Try this:

import json

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

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

f.close()

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

Upvotes: 1

Related Questions