Skip to content Skip to sidebar Skip to footer

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 par

Solution 1:

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
withopen("almost.json") as infile:
    jstring = infile.read()
data = json.loads(re.sub(r"(\w+):", r'"\1":', jstring))

Solution 2:

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)

Solution 3:

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

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

Post a Comment for "Python - Invalid Json Format - How To Parse"