lenhhoxung
lenhhoxung

Reputation: 2746

Invalid JSON objects from Twitter API in Python

I'm trying to obtain data from Twitter APIs. Following is the code in Python (I'm using TwitterAPI)

api = TwitterAPI(consumer_key, consumer_secret, access_token_key, access_token_secret)
r = api.request('search/tweets', {'q':'pizza'})
for item in r:
        print(item)

The code works and it prints the result. However, they aren't valid JSON objects. Actually, it contains additional "u" character, for example:

{u'contributors': None,
 u'truncated': False,
 u'text': u'RT
 @pizzaminati: Your smile.\nYour laugh.\nYour crust.\nYour sauce.\nYour
 cheese.\nYour toppings.\nYour jokes.\nYour weird faces.\nYour
 teasing.\nPi\u2026'...

I've worked with Twitter libs in Objective-C and it never responds strange results like that. Can you show me how to get valid JSON objects (I've also tried with Twython and got the same result)? And what is the best way to parse JSON objects in Python? Thank you.

Upvotes: 2

Views: 671

Answers (1)

nichochar
nichochar

Reputation: 2888

I'm assuming you're using python 2.X

This notation is just python's way of displaying unicode strings.

This may be clearer:

>>> type(u'hello world')
<type 'unicode'>
>>> type('hello world')
<type 'str'>

This should not be a problem if you're parsing the object in python and doing post processing in python. But if you're copying and pasting this into something else, it may be bothering you.

Unfortunately, the json module doesn't have a nice inbuilt way to give you strings instead of json, but this stackoverflow answer might help

Upvotes: 1

Related Questions