python 读写Json的中文编码问题

来源:互联网 发布:龙华新区行知实验小学 编辑:程序博客网 时间:2024/05/30 05:09

读写json文件:http://python3-cookbook.readthedocs.org/zh_CN/latest/c06/p02_read-write_json_data.html

首先 import json

load() loads()

dump() dumps()


一、从文件:

json转python数据结构:json.load

fo = open('data.json', 'r') data = json.load(fo)

python数据结构转json:json.dump

fo = open('data.json', 'r') json.dump(data, fo)

二、python字符串和json之间互相转换:

json_str = json.dumps(data)
data = json.loads(json_str)
三、json格式化输出:

1、格式化打印   pprint

2、格式化输出 

在编码JSON的时候,还有一些选项很有用。 如果你想获得漂亮的格式化字符串后输出,可以使用json.dumps() 的indent参数。 它会使得输出和pprint()函数效果类似。比如:

  print(json.dumps(data, indent=4))
fo = open('data.json', 'r') json.dump(data, fo, indent=4)

四、带有中文的json转换:

jsondata= json.dumps( dics, ensure_ascii = False, indent = 4 )

在dumps方法中加入参数ensure_ascii = False,可以使dic中的中文正常转换


2、若python的数据中既有普通字符,又有Unicode字符串,上述方法则不行,还要在后面加上encode('utf-8')

手动转换成utf-8编码

jsondata= json.dumps( dics, ensure_ascii = False, indent = 4 ).encode('utf-8')


http://stackoverflow.com/questions/18337407/saving-utf-8-texts-in-json-dumps-as-utf8-not-as-u-escape-sequence






0 0
原创粉丝点击