Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Invalid JSON format - how to parse

I am getting data in the following JSON format:

{
  address:[
    "test1"
  ],
  city:"test2",
  country:"test3",
  postal_code:"test4",
  state:"test5"
}

While I am trying to parse it via:

json.loads(data)

I am receiving an error: Expecting property name enclosed in double quotes

Is there a way to parse it in python ?

Thanks in advance,

like image 817
vba_user Avatar asked Sep 16 '25 16:09

vba_user


2 Answers

It goes without saying that the better solution would be to fix the broken data at the source. But if you can't do that, you could try and fix the problem with a simple regex. Simple, as in "will fail if you throw anything more complicated at it", but likely sufficient as a quick and dirty solution:

import re
import json
with open("almost.json") as infile:
    jstring = infile.read()
data = json.loads(re.sub(r"(\w+):", r'"\1":', jstring))
like image 112
Tim Pietzcker Avatar answered Sep 18 '25 05:09

Tim Pietzcker


The json standard needs the key with "", so you can't decode data with json module. However, you can do it with demjson (pip install demjson).

demjson.decode(data)
like image 28
chui Avatar answered Sep 18 '25 06:09

chui