5

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"
     }
]
}

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Dead link. Now at github.com/dmeranda/demjson and pretty inactive.
0

I am afraid that Python does not understand JavaScript. If you can use Node.js, it is easy to convert the input to JSON.

Edit: Of course you can also use the JavaScript console of every browser to do this.

> d = {
...  firstName:"John",
...  lastName:"Doe",
...  age:50,
...  eyeColor:"blue",
...  dimensions:[
...      {
.....       height: "2",
.....       width: "1"
.....      }
... ]
... };
{ firstName: 'John',
  lastName: 'Doe',
  age: 50,
  eyeColor: 'blue',
  dimensions: [ { height: '2', width: '1' } ] }
> JSON.stringify(d)
'{"firstName":"John","lastName":"Doe","age":50,"eyeColor":"blue","dimensions":[{"height":"2","width":"1"}]}'

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.