learningcompsci
learningcompsci

Reputation: 193

Cannot Convert JSON to Python List

I am a beginner at Python. I imported the Twitter test feed below, changed it to a JSON string, but am unable to convert it to a Python list. I tried 2 versions of code to do this, one of which I found on this site. They are listed below along with their output as well as a short segment of my input string. I would greatly appreciate any suggestions on how to fix this as it is unclear to me what I am doing wrong.

1)Subset of input string called tweet_text_list:

'[\'#mindset on #millionaire #goals #stocks #world #class\\xa0 #financial #boss #finesse #moves\\xa0 #study the #money #game… , "#Stocks #Investing #Stockmarket #nanoStockAnalysis Infosys\' (INFY) CEO Vishal Sikka on Q4 2017 Results - Earnin... ", \'RT @ElixiumNeptune: #Trading with #Bitcoin\#Forex #Stocks $ES $CL $GC $GOOG $AAPL $TSLA $SPY $QQQ…\']'

2)Code from this site:

import json

tweets_data = []

class JSONObject:
    def __init__( self, dict ):
        vars(self).update( dict )

tweets_data = json.loads(tweet_text_list, object_hook= JSONObject)

Output: JSONDecodeError: Expecting value: line 1 column 2 (char 1)

3)Another code attempt:

tweets_data = []

for line in tweet_list:
    try:
        tweet = json.loads(line) 
        tweets_data.append(tweet) 
    except:
        continue
print(tweets_data )

Output: []

Thank you very much for the help.

Upvotes: 0

Views: 118

Answers (2)

Ouroborus
Ouroborus

Reputation: 16865

'[\'#mindset on #millionaire #goals #stocks #world #class\\xa0 #financial #boss #finesse #moves\\xa0 #study the #money #game… , "#Stocks #Investing #Stockmarket #nanoStockAnalysis Infosys\' (INFY) CEO Vishal Sikka on Q4 2017 Results - Earnin... ", \'RT @ElixiumNeptune: #Trading with #Bitcoin\#Forex #Stocks $ES $CL $GC $GOOG $AAPL $TSLA $SPY $QQQ…\']'

That isn't a JSON encoded string. JSON only uses quotes, not apostrophes, to delimit strings. (You can find the JSON specification over here.)

The correct way to convert a Python value into JSON encoded string is via json.dumps(), as in:

tweet_text_list = json.dumps([tweet.text for tweet in tweet_list])

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191671

I used tweet_text_list=str([tweet.text for tweet in tweet_list])

That is a Python string. If you want a JSON string, give this a try.

tweets_json = json.dumps([tweet.text for tweet in tweet_list])

Upvotes: 1

Related Questions