【问题标题】:Receiving "TypeError: the JSON object must be str, bytes or bytearray, not dict"收到“TypeError:JSON 对象必须是 str、bytes 或 bytearray,而不是 dict”
【发布时间】:2019-08-27 21:56:40
【问题描述】:

我有一个来自 Tweepy 的 json 输出,我现在正试图解析它。例如,一些输出是特定区域的趋势标签。由于它是一个大输出,我正在尝试确定如何有效地解析所有主题标签。 json 输出中还有其他信息,例如useridcountrycode 等……但我只对列为name: '#gamenight 的主题标签感兴趣。

# using Tweepy

api.trends_place(2295420)

import json 

# Here is a portion of the Tweepy output I received
trends = [{'trends': [{'name': '#RCBvKKR', 'url': 'http://twitter.com/search?q=%23RCBvKKR', 'promoted_content': None, 'query': '%23RCBvKKR', 'tweet_volume': 101508}, {'name': 'created_at': '2019-04-06T00:07:14Z', 'locations': [{'name': 'Bangalore', 'woeid': 2295420}]}]

hashtags = json.dumps(trends)

# Am trying to end up with a way of just extracting 'name' which I believe is how the hashtags are captured 

print(hashtags['name'])

【问题讨论】:

    标签: python json tweepy


    【解决方案1】:

    接收#RCBvKKR应该是hastags["trends"][0]["name"]


    好的,我修好了。首先,发布的代码令人困惑。您发布的 json 无效,(括号丢失,名称键没有值)。其次,使用您的命令json.dumps(trends),您正在将已经有效的python字典转换为一个字符串,它是一个数组,因此出现错误,(string indices must be integers)

    固定版本是这样的:

    import json
    
    trends = [{'trends': [{'name': '#RCBvKKR', 'url': 'http://twitter.com/search?q=%23RCBvKKR', 'promoted_content': None, 'query': '%23RCBvKKR', 'tweet_volume': 101508}, {'name':"This was missing", 'created_at': '2019-04-06T00:07:14Z', 'locations': [{'name': 'Bangalore', 'woeid': 2295420}]}]}]
    
    
    print(trends[0]["trends"][0]["name"])
    

    现在输出是#RCBvKKR

    如果您确实从 API 收到了 json 字符串,请使用 json.parse(response) 将字符串转换为 python dict。

    【讨论】:

    • 我收到另一个错误 TypeError: string indices must be integers
    • @Tweep,是的,我修好了
    • 我认为我将收到的 Tweepy 输出错误地标记为 JSON,但我并不知道它是否正确。我仍在尝试确定 api.trends_place 的 Tweepy 输出格式。即它是一个数组,散列,json?
    • 我也在尝试检索“name”的每个实例,而不仅仅是“#RCBvKRR”
    猜你喜欢
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 2023-03-13
    • 2018-04-26
    • 1970-01-01
    • 2021-06-17
    • 2022-12-08
    相关资源
    最近更新 更多