Python-Solution to error when reading non-standard format json files

Not all files ending with .json have the data in the standard json format.
For example, the data format in the file named countries.json below is a non-standardized json data format.
Insert image description here
Note: In the json standard format, the string must be in double quotes, and the string in this file is in single quotes.
When reading such non-standard format json files, using the json module that comes with python will result in the following error:

import json
# json模块读取非标准格式json文件
with open('countries.json', 'r', encoding='utf-8') as f:
    data = json.load(f)
    print(data)

json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 2)
Insert image description here
Solution:
Use the python third-party module demjson, which can solve the format restriction problem of the json module and also includes the formatting of JSONLint and verification function.

How to use demjson is as follows:
1. demjson installation.
Open the command prompt (cmd), go to the Scripts file of the local installation python environment, enter the installation command and press Enter. The installation
command: pip install demjson
Insert image description here
2. Read
demjson from the json file. decode_file(), reads non-standard format json files and returns a dictionary (dict) format data.
For example, the above non-standard countries.json file reads:

# 非标准格式json文件读取
import demjson
data = demjson.decode_file('countries.json', encoding='utf-8')
print(data)
print("返回值类型:", type(data))

Insert image description here
Note: It can be seen that when using the json module to read non-standard json files and errors occur, the demjson third-party module can be used to solve the problem.

Follow [One Code] on WeChat to learn more about solutions to python-related problems.
-end-

Guess you like

Origin blog.csdn.net/LHJCSDNYL/article/details/125133746