pythonjsonjavascript-objects

JavaScript Object to JSON using python


I'm trying to retrieve what initially looked like a normal JSON from a website. But it is a JavaScript object which is not a valid JSON. Is there a way to convert this string to JSON using python?

Example would be:

{
 firstName:"John",
 lastName:"Doe",
 age:50,
 eyeColor:"blue",
 dimensions:[
     {
      height: "2",
      width: "1"
     }
]
}

Solution

  • Use a parser with a non-strict mode that can handle such input. I've been recommending demjson for stuff like this, since it's the first viable candidate that came up when I searched for python non-strict json parser.

    >>> demjson.decode("""{
    ...  firstName:"John",
    ...  lastName:"Doe",
    ...  age:50,
    ...  eyeColor:"blue",
    ...  dimensions:[
    ...      {
    ...       height: "2",
    ...       width: "1"
    ...      }
    ... ]
    ... }""")
    {u'eyeColor': u'blue', u'lastName': u'Doe', u'age': 50, u'dimensions': [{u'width
    ': u'1', u'height': u'2'}], u'firstName': u'John'}
    

    Until 2018, demjson was also hosted at http://deron.meranda.us/python/demjson/, now archived.