我有一个json文件,我正在尝试访问该值,但我一直收到一条错误,上面写着“TypeError:string indices必须是整数,而不是str”
这是Json数据。
{'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'] 打印数据将此返回给我
{
"0": {
"comment": "Chibok schoolgirls were swapped for 5 Boko Haram commanders",
"username": "@NigeriaNewsdesk:, @todayng",
"score": 0.0
}
}
但是当我尝试访问键/值对时,我收到错误 对于数据中的记录: 打印(记录[ “0”] [ “用户名”])
TypeError: string indices must be integers, not str
知道我为什么会收到这些错误吗?感谢
答案 0 :(得分:5)
在你发布的json中,sentiment
存储了json字符串,而不是json对象。你需要解析json - 例如json.loads(val['sentiment'])
,或将json存储为json对象。