Today to help the front-end to write a small background, is to read the data and then transferred to the JSON to give him, let him to show. The data is very simple, but the processing time encountered a problem, the file involved in the processing of Chinese, each processing finished writing JSON format is ASCII code, completely no way to use. The code is as follows:
#-*-Coding:utf-8-*-import jsonimport codecsf = Codecs.open (' data.txt ', ' r ', ' utf-8 ') content = Json.load (f) Print Conten t[0][' id ']jsdata = json.dumps (content, Sort_keys=true, indent=4) f.close () j = codecs.open (' Test.json ', ' W ') J.write ( Jsdata) J.close ()
Check the Web, the revised code is as follows:
#-*-Coding:utf-8-*-import jsonimport sysreload (SYS) sys.setdefaultencoding ("Utf-8") F = open (' Data.txt ', ' r ') content = Json.load (f) Print content[0][' id ']# stitching JSON data, transcoding to non-ASCII encoding jsdata = json.dumps (content, sort_keys=true, indent=4, ensure _ascii=false) F.close () j = open (' Test.json ', ' W ') J.write (jsdata) j.close ()
The above read and write JSON Chinese ASCII garbled problem solution is small part of the whole content to share to everyone, hope to give you a reference, but also hope that we support a lot of topic.alibabacloud.com.