Search code examples
pythonjsonsimplejson

Unable to use simplejson.loads() on a string


I am trying to use simplejson.loads(source_urls) to turn JSON into a Python object.

source_urls = [u'http://www.google.com', u'http://www.yahoo.com', u'http://www.facebook.com']

That line is from logger output. As much as that looks like a list, it is actually stored as a string in the database.

I get the following error:

JSONDecodeError:
Expecting object: line 1 column 1 (char 1)

Anyone have any thoughts?


Solution

  • Assuming you really have a single string source_urls containing:

    "[u'http://www.google.com', u'http://www.yahoo.com', u'http://www.facebook.com']"
    

    you can do:

    import ast
    urls = ast.literal_eval(source_urls)
    

    This will not allow true code execution. It only handles "strings, numbers, tuples, lists, dicts, booleans, and None".