SoFunction
Updated on 2024-11-21

Python JSON processing value error and encoding error of the two solution to the actual record!

1、ValueError: Invalid control character at: line 1 column 8363 (char 8362)
Appears when using (json_data):

ValueError: Invalid control character at: line 1 column 8363 (char 8362)

The error occurs because the string contains a carriage return character (\r) or a line feed character (\n)
Solution:
(1) Escape these characters:

json_data = json_data.replace('\r', '\\r').replace('\n', '\\n')

(2) Using the keyword strict.

(json_data, strict=False)

The default value of strict is True, which will strictly control internal strings. Setting it to False will allow you to \n \r.


2、UnicodeEncodeError: ascii codec can't encode error
Python scripts written under windows and run under linux report directly:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-11: ordinal not in range(128)

The reason for the error is that Python 2.7 is installed with ascii encoding by default, and when there are non-ascii encodings in the program, Python's processing will often report such an error, but there is no such problem in Python 3.
Solution:
(1) Interim solutions:
Add it before the code:
import sys 
reload(sys) 
('utf8')

(2) Once and for all:
Create a new one in Python's lib\site-packages folder with the following contents:

# encoding=utf8 
import sys 

reload(sys) 
('utf8')

In that case, the system calls this file on its own to set the system's default encoding when Python starts up.