vba_user
vba_user

Reputation: 125

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,

Upvotes: 4

Views: 13912

Answers (5)

chui
chui

Reputation: 61

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)

Upvotes: 6

x3mEr
x3mEr

Reputation: 33

You can use json5. JSON5 extends the JSON data interchange format to make it slightly more usable.

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

json5.loads(JsonStr)

out:

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

Upvotes: 1

Kailas cyberonics
Kailas cyberonics

Reputation: 1

'''''''

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

}

''''

Please change your code format to this , it will works

Upvotes: -2

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

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

Upvotes: 8

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

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

Upvotes: 1

Related Questions