简体   繁体   English

字符串索引必须是整数错误

[英]String indices must be integers error

I am looking to parse out json obtained from following code: 我想解析出从以下代码获得的json:

import json
from watson_developer_cloud import ToneAnalyzerV3Beta
import urllib.request
import codecs
reader = codecs.getreader("utf-8")
tone_analyzer = ToneAnalyzerV3Beta(
    url='https://gateway.watsonplatform.net/tone-analyzer/api',
    username='<username>',
    password='<password>',
    version='2016-02-11')

data=json.dumps(tone_analyzer.tone(text='I am very happy'), indent=2)
print (data)

for cat in data['document_tone']['tone_categories']:
    print('Category:', cat['category_name'])
    for tone in cat['tones']:
        print('-', tone['tone_name'])

and keep running into error:string indices must be integers Not sure where I am dropping the ball but I would really appreciate any help with this one. 并不断出错:字符串索引必须是整数不确定我在哪里丢球,但我真的很感谢这个帮助。

json.dumps() converts an object into a string. json.dumps()将对象转换为字符串。 So, data is a string. 因此, data是一个字符串。 So, you can't index it with 'document_tone' key (it's not a dict ). 因此,您不能使用'document_tone'键对其进行索引(这不是dict )。 Maybe you meant json.loads() ? 也许你是说json.loads() Or maybe tone_analyzer.tone() already returns a dict and there is no need for loads() ? 或者, tone_analyzer.tone()已经返回了一个dict并且不需要loads()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM