Python中已有一个dict对象的json变量
其中部分key的值中包含中文
现在希望可以把dict打印出,格式化之后,带缩进的字符串
且中文也希望正常显示
之前已经通过:
def jsonToStr(jsonDict, indent=2): return json.dumps(jsonDict, indent=2) |
把:
respAccessTokenStr = jsonToStr(respAccessToken) app.logger.debug(‘respAccessTokenStr=%s’, respAccessTokenStr) |
打印为:
respAccessTokenStr={ "access_token": "QWRsxLLAAmU_wv_rXnz5pQDW7pGKtlAIR5YLv2_upTlsSsf1Iw21nACVKEmra53V0X2wC71ZT2E2VLKmibM8Ioai31bQWb5Mfk4NSjnIZfA", "openid": "oswjmv4X0cCXcfkIwjoDfCkeTVVY", "expires_in": 7200, "refresh_token": "_EoUSHba6rx7QTsPRUtxUEbBOW_f_IFUxOiE5_5slybMa6B2D0ePW5NdEst_3oVvRkTZbW0nGTmyUOQMx11Dlq3X0VT6tLMY8LHpFDOhWR8", "scope": "snsapi_userinfo" } |
即,对于英文,已经OK了。
且带了缩进了。
但是后来遇到中文:
respUserInfoStr = jsonToStr(respUserInfoDict) app.logger.debug(‘type(respUserInfoStr)=%s, respUserInfoStr=%s’, type(respUserInfoStr), respUserInfoStr) |
打印出来的却是unicode值:
type(respUserInfoStr)=<type ‘str’>, respUserInfoStr={ "province": "\u6c5f\u82cf", "openid": "oswjmv4X0cCXcfkIwjoDfCkeTVVY", "headimgurl": "http://wx.qlogo.cn/mmopen/ajNVdqHZLLDYtIJicNl7MjwZK5c1lxAJZ253c9v3JzDib7GeE5OFrWiaRqsK1ruW1HmGaziaYETV5vQhIIbic6wHKFQ/0", "language": "zh_CN", "city": "\u82cf\u5dde", "country": "\u4e2d\u56fd", "sex": 1, "privilege": [], "nickname": "\u793c\u8c8c" } |
后来,想到了,别人在别处,使用到了json.dumps的参数ensure_ascii
其设置为了false
而此处,注意到其默认为True:
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, encoding=’utf-8′, default=None, sort_keys=False, **kw): |
所以去试了试,此处也去设置ensure_ascii为False
def jsonToStr(jsonDict, indent=2): return json.dumps(jsonDict, indent=2, ensure_ascii=False) |
然后也就可以正常输出带缩进的json,且正常显示中文字符了:
type(respUserInfoStr)=<type ‘unicode’>, respUserInfoStr={ "province": "江苏", "openid": "oswjmv4X0cCXcfkIwjoDfCkeTVVY", "headimgurl": "http://wx.qlogo.cn/mmopen/ajNVdqHZLLDxxxxxxxxxxxxxxxxxxxxxKFQ/0", "language": "zh_CN", "city": "xxx", "country": "中国", "sex": 1, "privilege": [], "nickname": "xxx" } |
[总结]
要让json格式化输出为字符串,且正常显示中文的话,可以用:
def jsonToStr(jsonDict, indent=2): return json.dumps(jsonDict, indent=2, ensure_ascii=False) |
即可。
用法举例:
formatedJsonStrWithIndentAndShowZhcnOk = jsonToStr(someJsonDict) print formatedJsonStrWithIndentAndShowZhcnOk |