SoFunction
Updated on 2024-11-16

Solve python3 json data contains Chinese read and write problems

python3 defaults to UTF-8 format, but you should still be careful when writing with dump: as follows

import json
data1 = {
 "TestId": "testcase001",
 "Method": "post",
 "Title": "Login Test",
 "Desc": "Login benchmarking",
 "Url": "",
 "InputArg": {
  "username": "Wang Xiaoya",
  "passwd": "123456",
 },
 "Result": {
  "errorno": "0"
 }
}
with open('', 'w', encoding='utf-8') as f:
  (data1, f, sort_keys=True, indent=4)

You have to add encoding='utf-8' when you open the file, otherwise it will be displayed as a garbled code, as follows:

{
 "Desc": "��¼��׼����",
 "InputArg": {
  "passwd": "123456",
  "username": "��СѾ"
 },
 "Method": "post",
 "Result": {
  "errorno": "0"
 },
 "TestId": "testcase001",
 "Title": "��¼����",
 "Url": ""
}

Also add ensure_ascii=False when dumping, otherwise it will become ascii code to be written to the file, as follows:

{
 "Desc": "\u767b\u5f55\u57fa\u51c6\u6d4b\u8bd5",
 "InputArg": {
  "passwd": "123456",
  "username": "\u738b\u5c0f\u4e2b"
 },
 "Method": "post",
 "Result": {
  "errorno": "0"
 },
 "TestId": "testcase001",
 "Title": "\u767b\u5f55\u6d4b\u8bd5",
 "Url": ""
}

In addition python3 in to the txt file to write Chinese also need to pay attention to open with encoding='utf-8', otherwise it is also messy code, as follows:

with open('', 'a+', encoding='utf-8') as rst:
  ('return data')
  ('|')
  for x in ():
    (x[0])
    (':')

For more information about solving python3 json data containing Chinese read/write and messy code problems please check the following related links