0

I am confident that with JSON data the keys should be surrounded by double quotes (")

However when I was scraping a certain website, I had to extract the data from a javascript variable which I assumed it to be a JavaScript Object.

The data was similar to this one.

d = '{device:"2","wew":"xxx"}'

As you can see the first key is not surrounded by double quotes and I was thinking of getting this converted to a python dictionary.

If you perform a json.loads(d) directly you'll be having an error.

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

I have made a possible solution to str.replace('device:','"device":') then perform a json.loads(d) which works fine.

But I am conflicted by the fact that how can we at least put double quotes on every key on the JavaScript Object string whatever the key is. Is there a way to do this? Is there an existing built in python package to get the job done? I have tried searching about this but this is all I find.

martineau
  • 112,593
  • 23
  • 157
  • 280
Ice Bear
  • 1,414
  • 7
  • 20
  • The suggested answer is great! I would prefer to use ```json5``` from this [answer](https://stackoverflow.com/a/65645926/14425271) – Ice Bear Feb 23 '22 at 04:39

0 Answers0