'Converting JavaScript JSON data to Python JSON

I have JavaScript JSON data:

var data = '{a: 10, b: 20}'

I want to convert it to Python JSON. How can I do?

My situation: I have script that read text from a website. website has data in javascript variables like I show in example. I extracted variable part '{a: 10, b: 20}'. But for the python, it is still string format. I need to convert that data into Python JSON so I can do further work.

How can I convert JavaScript JSON to Python JSON?



Solution 1:[1]

Python JSON is a bit of a misnomer as JSON (as in JavaScript Object Notation) is a subset of JavaScript and simply describes a JavaScript object. It is an exchange format that does not depend on the language you are using it with.

You can use the json module to parse JSON in Python, and return an equivalent Python object.

Solution 2:[2]

Apparently some libraries like RSON can help you.

According to that answer

Solution 3:[3]

var data = '{a: 10, b: 20}' is not a valid JSON. It is valid JavaScript

If you were to do

var data = JSON.stringify({ a: 10, b: 20 });

you would find it actually becomes

var data = '{ "a": 10, "b": 20 }'

The extra " around the a and b variables being the part that makes this valid JSON. The confusion comes from the fact that JavaScript is more forgiving than JSON.

Don't feel bad. You will not be the only one who will fall into this trap.

Solution 4:[4]

it need regex replace before can convert it json

import re
import json

data = '''{a: 10, b: true, c :"string", "d" : jsVariable, e:'single'}'''

# replace single with double quote
data = data.replace("'", '"')

# wrap key with double quotes
data = re.sub(r"(\w+)\s?:", r'"\1":', data)

# wrap value with double quotes
# but not for interger or boolean
data = re.sub(r":\s?(?!(\d+|true|false))(\w+)", r':"\2"', data)

data = json.loads(data)

print(data['a']) # 10
print(json.dumps(data, indent=2)) # formatted json string

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alexander Gessler
Solution 2 Community
Solution 3 WORMSS
Solution 4 uingtea