I have a string with js code
[{label: ' ', name: 'Confirmed', width: 30, formatter: 'checkbox'},{label: 'ID', name: 'ID', width: 100, key:true},{label: 'E-mail', name: 'F250275', width: null, formatter: clearText},{label: 'Agree', name: 'F250386', width: null, formatter: clearText},]
Is there a way to parse it to python to get list? I’ve tried json.loads , but get the error json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 3 column 18 (char 27)
Some update, based on comments.
There isn’t any options to use JS here. That’s why I didn’t put JS tag here
13
Here is the package for such things https://pypi.org/project/calmjs.parse/
Some example
from calmjs.parse.unparsers.extractor import ast_to_dict
from calmjs.parse import es5
my_string_with_js = "here is js code from the question"
configuration = es5(my_string_with_js)
baseconf = ast_to_dict(configuration)
If it’s this same general format, you can attempt to convert it to valid JSON by quoting the property names and converting the single quotes to double quotes.
Here’s some demo code:
import re
import json
def js2json(str):
l = [];
objs = re.findall(r"({[^}]*})", str); # get objects
for obj in objs:
obj = re.sub(r"([{,]s*)([a-zA-Z0-9_]+)", r'1"2"', obj); # quote object property names
obj = re.sub(r"(:s*)'?([^',}]+)'?", r'1"2"', obj); # quote object property values
l.append(json.loads(obj))
return l
str="[{label: ' ', name: 'Confirmed', width: 30, formatter: 'checkbox'},{label: 'ID', name: 'ID', width: 100, key:true},{label: 'E-mail', name: 'F250275', width: null, formatter: clearText},{label: 'Agree', name: 'F250386', width: null, formatter: clearText},]"
print(js2json(str))