Two solutions to the error and coding errors of Python when processing JSON

Source: Internet
Author: User
1, valueerror:invalid control character at:line 1 column 8363 (char 8362)
When using Json.loads (Json_data), it appears:

Valueerror:invalid control character at:line 1 column 8363 (char 8362)

The error occurs because the string contains a carriage return (\ r) or a newline character (\ n)
Workaround:
(1) Escaping these characters:

Json_data = Json_data.replace (' \ R ', ' \\r '). replace (' \ n ', ' \\n ')

(2) Use keyword strict:

Json.loads (Json_data, Strict=false)

The strict default is true, which tightly controls the internal string and sets it to false to allow you \ r.


2, Unicodeencodeerror:ascii codec can ' t encode error
A Python script written under Windows that runs under Linux and reports directly:

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

The reason for the error is that Python2.7 at the time of installation, the default encoding is ASCII, when non-ASCII encoding occurs in the program, Python processing often reported such an error, but there is no such problem in Python3.
Workaround:
(1) Temporary solution:
Before the code, add:

Import sys reload (SYS) sys.setdefaultencoding (' UTF8 ')

(2) Once and for all:
Create a new sitecustomize.py under the Python lib\site-packages folder, as follows:

# ENCODING=UTF8 Import sys reload (SYS) sys.setdefaultencoding (' UTF8 ')

In this case, the system calls the file itself when the python is started and sets the system's default encoding.

  • 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.