Format json string to work with json.loads()

by mnmmeng   Last Updated July 13, 2019 01:26 AM

I have received a json format string from a API like below:


string = ' {\n  "Ids": ["abc-765"],\n  "Type": "Column",\n  "Number": "021649015",\n  "Code": "02109998000",\n  "Text": , \n}'

Trying to get it work with json.loads but getting error:

JSONDecodeError: Expecting value: line 6 column 20 (char 162)

I think it's because of the missing value in the last key, and the additional tailing comma.

Is there a way I could format the string to get it working with json.loads?



Answers 1


It isn't possible without making some assumptions. All of those assumptions need to be true for this algorithm to work:

  • First line is always only {
  • Last line is always only }
  • All other lines contain exactly one key-value pair of the dictionary
import json


def fix_json(string):
    modifiedLines = []
    for line in string.splitlines()[1:-1]:
        line = line.strip()
        if line.endswith(','):
            line = line[:-1].strip()
        if line.endswith(':'):
            line = line + "null"
        modifiedLines.append(line)
    return '{\n' + ',\n'.join(modifiedLines) + '\n}'


string = ' {\n  "Ids": ["abc-765"],\n  "Type": "Column",\n  "Number": "021649015",\n  "Code": "02109998000",\n  "Text": , \n}'

modifiedString = fix_json(string)
jsonData = json.loads(modifiedString)
print(jsonData)
{'Ids': ['abc-765'], 'Type': 'Column', 'Number': '021649015', 'Code': '02109998000', 'Text': None}
Finomnis
Finomnis
July 13, 2019 01:19 AM

Related Questions




Post request won't send

Updated June 03, 2019 14:26 PM