简体   繁体   中英

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,

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))

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

demjson.decode(data)

Your variables should be like "address" or "city".

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

'''''''

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

}

''''

Please change your code format to this, it will works

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM