0

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

import json

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

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

f.close()

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

1 Comment

no need to use .loads(), .load() is not the issue here.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.