kev kev - 28 days ago 12
Javascript Question

How to convert raw javascript object to python dictionary?

When screen-scraping some website, I extract data from

<script>
tags.

The data I get is not in standard
JSON
format. I cannot use
json.loads()
.

# from
js_obj = '{x:1, y:2, z:3}'

# to
py_obj = {'x':1, 'y':2, 'z':3}


Currently, I use
regex
to transform the raw data to
JSON
format.

But I feel pretty bad when I encounter complicated data structure.

Do you have some better solutions. Thanks for share!

kev kev
Answer

demjson.decode()

import demjson

# from
js_obj = '{x:1, y:2, z:3}'

# to
py_obj = demjson.decode(js_obj)

jsonnet.evaluate_snippet()

import json, _jsonnet

# from
js_obj = '{x:1, y:2, z:3}'

# to
py_obj = json.loads(_jsonnet.evaluate_snippet('snippet', js_obj))

ast.literal_eval()

import ast

# from
js_obj = "{'x':1, 'y':2, 'z':3}"

# to
py_obj = ast.literal_eval(js_obj)
Comments