0

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

2
  • What is records? I believe you want print(data["0"]["username"]). Commented Jun 5, 2017 at 21:29
  • Firstly the value of "sentiment" key is string and not a dict object. Secondly, it is not even a valid JSON string. You should fix the logic where you are storing this value. Probably store it as a dict or at least as valid JSON string Commented Jun 5, 2017 at 21:35

1 Answer 1

5

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.

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

1 Comment

it won't work because the so called JSON string mentioned in the question is having incorrect format

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.