0

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.

2
  • "Changed it to a JSON string"... How did you do that? Because you don't have a JSON string here Commented Apr 14, 2017 at 3:27
  • I used tweet_text_list=str([tweet.text for tweet in tweet_list]) Commented Apr 14, 2017 at 3:32

2 Answers 2

1

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])
Sign up to request clarification or add additional context in comments.

Comments

1

'[\'#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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.