JavaScript object to JSON using python

I'm trying to extract initially what initially looked like regular JSON. But it is a JavaScript object that is not valid JSON. Is there a way to convert this string to JSON using python?

Example:

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

      

+3


source to share


3 answers


Use a lax-mode parser that can handle this input. I recommend demjson for things like this as it is the first viable candidate that came up when I was looking 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'}

      

+5


source


I'm afraid Python doesn't understand JavaScript. If you can use Node.js it is easy to convert the input to JSON.

Edit: Of course, you can also use a per-browser JavaScript console.



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

      

0


source


You can convert using json

the python library.

>>> a = {'firstName':"John", 'lastName':"Doe", 'age':50, 'eyeColor':"blue", 'dimensions':[     {'height': "2", 'width': "1"}]}
>>> import json
>>> json.dumps(a)
'{"eyeColor": "blue", "lastName": "Doe", "age": 50, "dimensions": [{"width": "1", "height": "2"}], "firstName": "John"}'
>>>

      

And if you have a json formatted string

>>> a = '{"eyeColor": "blue", "lastName": "Doe", "age": 50, "dimensions": [{"width": "1", "height": "2"}], "firstName": "John"}'
>>> json.loads(a)
{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'}

      

this will return u valid python dict

-2


source







All Articles