mac389
mac389

Reputation: 3133

Decoding JSON file from Twitter in Python using simplejson

A small part of my JSON file looks like the following. It passed a JSON validator. (I added cl

{
"next_page": "?page=2&max_id=210389654296469504&q=cocaine&geocode=40.665572%2C-73.923557%2C10mi&rpp=100",
"completed_in": 0.289,
"max_id_str": "210389654296469504",
"since_id_str": "0",
"refresh_url": "?since_id=210389654296469504&q=cocaine&geocode=40.665572%2C-73.923557%2C10mi",
"results": [
    {
        "iso_language_code": "en",
        "to_user_id": 486935435,
        "to_user_id_str": "486935435",
        "profile_image_url_https": "https://si0.twimg.com/profile_images/1561856049/Zak_W_Photo_normal.jpg",
        "from_user_id_str": "82389940",
        "text": "@Bill__Murray cocaine > productivity! Last night I solved the euro crisis and designed a new cat. If I could only find that napkin.",
        "from_user_name": "Zak Williams",
        "in_reply_to_status_id_str": "210319741322133504",
        "profile_image_url": "http://a0.twimg.com/profile_images/1561856049/Zak_W_Photo_normal.jpg",
        "id": 210389654296469500,
        "to_user": "Bill__Murray",
        "source": "<a href="http://twitter.com/#!/download/iphone" rel="nofollow">Twitter for iPhone</a>",
        "in_reply_to_status_id": 210319741322133500,
        "to_user_name": "Bill Murray",
        "location": "Brooklyn",
        "from_user": "zakwilliams",
        "from_user_id": 82389940,
        "metadata": {
            "result_type": "recent"
        },
        "geo": "null",
        "created_at": "Wed, 06 Jun 2012 15:16:17 +0000",
        "id_str": "210389654296469504"
    }
]
}

When I try to load this in Python by typing the following code I get the following error.

Code

 import simplejson as json
 testname = 'test.txt'
 record = json.loads(testname)

Error

 raise JSONDecodeError("No JSON object could be decoded", s, idx)
 simplejson.decoder.JSONDecodeError: No JSON object could be decoded: line 1 column 0 (char 0)

What am I doing wrong? In fact, I generated the file by using simplejson.dump

Upvotes: 2

Views: 1074

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 994531

The json.loads() function loads JSON data from a string, and you are just giving it a file name. The string test.txt is not a valid JSON string. Try the following to load JSON data from a file:

with open(testname) as f:
    record = json.load(f)

(If you're using an old version of Python that doesn't support the with statement (as possibly indicated by your use of the old simplejson), then you'll have to open and close the file yourself.)

Upvotes: 2

Related Questions