程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python-non-standard format json file reading error solution

編輯:Python

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-


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved