PythonRookie
PythonRookie

Reputation: 311

Accessing Json values Python

I have a json file, and i am trying to access the value, but i keep getting an error that says "TypeError: string indices must be integers, not str"

This is the Json data.

{'sentiment': '{\n  "0": {\n    "comment": "Chibok schoolgirls were swapped for 5 Boko Haram commanders \n    "username": "@NigeriaNewsdesk:, @todayng", \n    "score": 0.0\n  }\n}'}

data = val['sentiment'] printing data returns this back to me

{
 "0": {
  "comment": "Chibok schoolgirls were swapped for 5 Boko Haram commanders", 
  "username": "@NigeriaNewsdesk:, @todayng", 
  "score": 0.0
 }
}

But when i try to access the key/value pairs, i get an error for records in data: print(records["0"]["username"])

TypeError: string indices must be integers, not str

Any idea why i am getting these errors? Thanks

Upvotes: 0

Views: 703

Answers (1)

Orphid
Orphid

Reputation: 2852

In the json you posted, sentiment stores a json string, not a json object. You need to parse the json - e.g. json.loads(val['sentiment']), or store the json as a json object.

Upvotes: 5

Related Questions