json.decoder.JSONDecodeError: Invalid control character when we try to parse a JSON

Question:

json.decoder.JSONDecodeError: Invalid control character error when i try to parse a JSON string.

import json
import pprint

json_data = None
with open("C:\Users\75\OneDrive\PROJECT P1\Work_1.0\CBP\server.txt", 'r') as f:
    data = f.read()
    json_data = json.loads(data)

pprint.pprint(json_data)
f.close()
jsonString = json.dumps(json_data,default = str)
jsonFile = open("converted.json", "w")
jsonFile.write(jsonString)
jsonFile.close()

Requirement is to import unformatted dump data from a text file and convert into JSON and write it into a .json file using python

Getting below error

Traceback (most recent call last):
  File "C:\Users\75\OneDrive\PROJECT P1\Work_1.0\CBP\server.txt", line 11, in <module>
    json_data = json.loads(data)
  File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0libjson__init__.py", line 346, in loads    
    return _default_decoder.decode(s)
  File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0libjsondecoder.py", line 337, in decode    
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:Program FilesWindowsAppsPythonSoftwareFoundation.Python.3.9_3.9.3568.0_x64__qbz5n2kfra8p0libjsondecoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Invalid control character at: line 1 column 124 (char 123)
Asked By: Tono Kuriakose

||

Answers:

I had encountered same and To solve the error, set the strict keyword argument to False in the call to json.loads().

json_data = json.loads(data, strict=False)

so your code could be like below:

import json
import pprint

json_data = None
with open("C:\Users\75\OneDrive\PROJECT P1\Work_1.0\CBP\server.txt", 'r') as f:
    data = f.read()
    json_data = json.loads(data, strict=False)

pprint.pprint(json_data)
f.close()
jsonString = json.dumps(json_data,default = str)
jsonFile = open("converted.json", "w")
jsonFile.write(jsonString)
jsonFile.close()
Answered By: Felix
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.