Python implementation of json file reading and Chinese scrambled code display problem solution

  • 2020-12-07 04:05:57
  • OfStack

An example of Python implementation of json file reading and Chinese scrambled code display problem solution. To share for your reference, the details are as follows:

The city.json file reads as follows:


{
 "cities": [
  {
   "city": " Beijing ",
   "cityid": "101010100"
  },
  {
   "city": " Shanghai ",
   "cityid": "101020100"
  }
  ]
}

As you can see, it contains Chinese.

Python use json.loads After that, there will be the problem of messy code in Chinese printing. The solution is as follows:


with open('city.json', 'r') as json_file:
  """
   Read the json When file, follow first gbk The way to decode and re-encode for it is utf-8 The format of the 
  """
  data = json_file.read().decode(encoding='gbk').encode(encoding='utf-8')
  print type(data)  # type(data) = 'str'
  result = json.loads(data)
  new_result = json.dumps(result,ensure_ascii=False) #  Referring to the online method, ***ensure_ascii*** Set to False
  print new_result
#  Output results: 
# "cities": [{"cityid": "101010100", "city": " Beijing "}, {"cityid": "101020100", "city": " Shanghai "}]

PS: Here are some more practical json online tools for your reference:

Online JSON code inspection, inspection, beautification, formatting tools:
http://tools.ofstack.com/code/json

JSON Online formatting tools:
http://tools.ofstack.com/code/jsonformat

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

json code online formatting/beautification/compression/editing/conversion tools:
http://tools.ofstack.com/code/jsoncodeformat

Online json compression/escape tool:
http://tools.ofstack.com/code/json_yasuo_trans

More Python related content interested readers to view this site project: "Python json operation skills summary", "Python coding skills summary", "Python data structure and algorithm tutorial", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article is helpful for Python programming.


Related articles: