Convert a JSON object containing Chinese characters to a string

Source: Internet
Author: User

During development and testing, it is often necessary to convert a JSON object containing Chinese characters into a JSON string. If you use STR (json_obj) or JSON. dumps (json_obj) Conversion generates: {'A': {'B': U' \ u4e2d \ u6587 '}, but the result is: {'A': {'B': 'Chinese '}}.

In the early stage, a nested traversal object method was used to extract Chinese characters and splice them into strings. The method was a bit clumsy. See http://hiying.net/post-32.html

 

In this improvement, convert the string to: {'A': {'B': U' \ u4e2d \ u6587 '}, and then use a regular expression to retrieve the string starting with \ U, then convert them into Chinese characters one by one, and finally replace

Def json_to_str (OBJ ):
"Converts a JSON object to a string to solve the problem of an error in STR () or JSON. dumps () Chinese """
Import re
Ret = ""
# Replace the u before the Chinese Character
String = STR (OBJ). Replace ("U'", "'"). Replace ('U "','"')
# Regular Expression
P = Re. Compile (R' \ U [0-9a-fa-f] {4 }')
# Obtain all matched strings, such as \ u4e2d
Cn_chars = P. findall (string)
For C in cn_chars:
String = string. Replace (C, u_converter (C [2:])
Return string

Def u_converter (c ):
"Conversion of a single Chinese character """
If Len (c ):
Try:
Ncode = int (C, 16)
Except t:
Pass
Try:
Uchar = unichr (ncode)
Except t:
Pass
Return uchar

Reprinted from: Method for converting a JSON object containing Chinese characters into a string (2)

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.