mLC
mLC

Reputation: 693

How to convert JSON string with "" (instead of ") to JSON in Python

I have a string:

a = '"{""key1"": ""val1"", ""key2"":""val2""}"'

What is the most propriate way to convert this to a dictionary in Python?

plain json.loads(a) cannot decipher this format.

EDIT: This weird JSON string is created when I read a CSV with one "json-like" column.

Upvotes: 0

Views: 127

Answers (4)

mLC
mLC

Reputation: 693

The @chepner's answer actually sent me in the right direction. The string was loaded from CSV and I could effectively prevent this weird JSON forming by using answer from here: spark 2.0 read csv with json, i.e. add the escape char '\"' option.

Thanks for the answers - they all work :)

Upvotes: 0

chepner
chepner

Reputation: 532003

Assuming the string came from a CSV file, use csv to decode it before passing the result to json for decoding.

>>> import io, csv, json
>>> a = '"{""key1"": ""val1"", ""key2"":""val2""}"'
>>> csv_file_like = io.StringIO(a)
>>> reader = csv.reader(csv_file_like)
>>> result = list(reader)
>>> json.loads(result[0][0])
{'key1': 'val1', 'key2': 'val2'}

This is a little simpler if a was already set by reading from a CSV file; you can skip using io to create a file-like object from a and use csv.reader directly on the original CSV file.

Upvotes: 3

balderman
balderman

Reputation: 23825

Try

import json
a = '"{""key1"": ""val1"", ""key2"":"val2""}"'
a = a.replace('""','"').replace('}"',"}").replace('"{','{')
data = json.loads(a)
print(data)

output

{'key1': 'val1', 'key2': 'val2'}

Upvotes: 0

ocheriaf
ocheriaf

Reputation: 600

I don't know this kind of format for json. So you can use the next function :

import json
def load_weird_json(json_string):
    a = json_string.replace('""','"')
    a = a[1:len(a)-1]
    return json.loads(a)

Upvotes: 1

Related Questions