The value error and encoding error when processing JSON in Python solve the real-time recording problem.

Source: Internet
Author: User
This article mainly introduces two methods to solve the real-time recording problem: the value error when processing JSON and the encoding error. here, I suggest using Python 3.x, python3's default Unicode encoding can save us a lot of trouble in actual use. For more information, see 1. ValueError: Invalid control character at: line 1 column 8363 (char 8362)
When json. loads (json_data) is used, the following error occurs:

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

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

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

(2) use the keyword strict:

json.loads(json_data, strict=False)

Strict is True by default. it strictly controls internal strings and sets it to False to allow \ n \ r.


2. UnicodeEncodeError: ascii codec can't encode error
Run the python script written in windows in linux and report it directly:

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

The cause of the error is that during installation of Python2.7, the default encoding is ascii. when non-ascii encoding occurs in the program, this error is often reported during Python processing, however, this problem does not occur in Python3.
Solution:
(1) temporary solution:
Add:

import sys reload(sys) sys.setdefaultencoding('utf8')

(2) once and for all:
Create a new sitecustomize. py in the lib \ site-packages folder of Python. the content is as follows:

# encoding=utf8 import sys reload(sys) sys.setdefaultencoding('utf8')

In this case, when the system starts Python, it calls the file and sets the default encoding of the system.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.