Not all files ending with .json contain data in standard json format.
For example, the following data format in the countries.json file is a non-standardized json data format.
Note: In the json standard format, the string must useDouble quotes, this file string is single quotes.
When reading such non-standard format json files, using the json module that comes with python, the following error will be reported:
import json# The json module reads non-standard format json fileswith 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)
Solution:
Use the python third-party module demjson, which can solve the format limitation of the json module, and also includes the JSONLintFormatting and verification functions.
The usage of demjson is as follows:
1. demjson installation
Open the command prompt (cmd), enter the Scripts file of the local installation python environment, enter the installation command and returncar,
Installation command: pip install demjson
2. json file reading
demjson.decode_file(), reads the json file in non-standard format, and returns a dictionary (dict) format data.
For example, the above non-standard countries.json file reads:
# Non-standard format json file readingimport demjsondata = demjson.decode_file('countries.json', encoding='utf-8')print(data)print("Return value type:", type(data))
Note: Visible, use json module to read non-standardWhen there is an error in the json file, you can use the demjson third-party module to solve it.
WeChat pays attention to [one code] to learn more about python-related problems.
-end-