Receiving "TypeError: the JSON object must be str, bytes or bytearray, not dict"
It should be hastags["trends"][0]["name"]
to receive #RCBvKKR
Okay I fixed it. First, the posted code is confusing. The json you posted is not valid, (brackets are missing and name key has no value). Second , with your command json.dumps(trends)
, You are converting already valid python dictionary to a string, which is an array, thus the error, (string indices must be integers
)
The fixed version is like this:
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"])
Now the output is #RCBvKKR
If you indeed receive a json string from the API, use json.parse(response)
to convert string to python dict.
Tweep
Updated on June 27, 2022Comments
-
Tweep almost 2 years
I have a json output from Tweepy, which I'm now trying to parse through. For instance, some of the output are trending hashtags for a particular area. Since it is a large output, I'm trying to determine how to efficiently parse through all of the hashtags. There is other information in the json output such as
userid
,countrycode
, etc... But I'm only interested in the hashtags which are listed asname: '#gamenight
for instance.# 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'])
-
Tweep about 5 yearsI received another error TypeError: string indices must be integers
-
atakanyenel about 5 years@Tweep , yep I fixed it
-
Tweep about 5 yearsI think i mislabeled the Tweepy output I received as JSON, without really knowing if it was or not. I'm still trying to identify what format Tweepy output for api.trends_place comes in as. i.e. is it an array, hash, json?
-
Tweep about 5 yearsI'm also trying to retrieve every instance of 'name' not just '#RCBvKRR'