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)