www.cnblogs.com/ruiyqinrui

开源、架构、Linux C/C++/python AI BI 运维开发自动化运维。 春风桃李花 秋雨梧桐叶。“力尽不知热 但惜夏日长”。夏不惜,秋不获。@ruiY--秦瑞

python爬虫,C编程,嵌入式开发.hadoop大数据,桉树,onenebula云计算架构.linux运维及驱动开发.

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

现在以 json 为数据传输格式的 RESTful 接口非常流行。为调试这样的接口,一个常用的办法是使用 curl 命令:

curl http://somehost.com/some-restful-api

对于返回的 json 字符串,一般在服务端不加处理的情况下,都是没有任何 '\t' 和 '\n' 的。为了方便查看,在 bash 上可以简单地对它进行格式化:

curl http://somehost.com/some-restful-api | python -mjson.tool

当然这要求机器上安装了 python,其实也就是利用了 json.tool 这个程序。

然而有时候还有一个问题,就是若返回的 json 字符串中包含中文,那么这样打印出来之后,中文会变成以 \u 开头的转义形式,从而让程序员无法直接观察到中文的内容。这并非是一个 bug,而是 json 本身的标准,它要求 json 的内容都是 ascii 编码的。标准的 json 编码器和解码器都会遵循这一点。

解决这个问题的办法是编辑 json.tool 程序,该程序存在于 python 系统库安装路径下的 json/tool.py。在 main 方法的最后,将:

json.dump(obj, outfile, sort_keys=True, indent=4)

修改为:

json.dump(obj, outfile, sort_keys=True, indent=4, ensure_ascii=False)

即让 json.tool 程序不强行保证 json 的内容都转义为 ascii 编码。修改后,再次运行

curl http://somehost.com/some-restful-api | python -mjson.tool

打印的结果即可正常包含中文。

不过这样还是会有问题,当返回的 json 字符串中包含了一些类似 emoji 表情这种无法正常编码的字符时,将结果打印到 bash 没问题,但是一旦打印到 less 或者文件上,则会提示编码错误:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-2: ordinal not in range(128)

解决办法,手动在 json.tool 程序中编码。在 json/tool.py 的最后,修改为(需提前 import codecs):

s = json.dumps(obj, sort_keys=True, indent=4, ensure_ascii=False)
outfile.write(codecs.encode(s, 'utf-8'))

这样就可以了。

gist: https://gist.github.com/nicky-zs/6af8a1afc771ad76d463

 

posted on 2017-03-09 14:40  秦瑞It行程实录  阅读(1905)  评论(0编辑  收藏  举报
www.cnblogs.com/ruiyqinrui