对json.tool工具的改进

自从用了mac后,就渐渐喜欢上了命令行,利用管道,可以把一些基本命令组合在一起,发挥意想不到的效果. 在接口调试中,我常用的是curl工具. 通常返回一串json数据,但有时数据量过大,且返回的json并没有格式化。可用python自带的工具对其进行格式化处理:

curl -XGET 'http://*****' |  python -m json.tool

以上命令通过管道将curl的执行结果传递给 json.tool 执行,输出的结果确实起到格式化的作用,但中文可读性全无。
前不久,我想通过shell脚本调用公司的某一接口。前置条件是要通过登陆接口获取token(token是登陆接口返回json中的一个字段)。接口还涉及到base64加密,以及用md5计算摘要。base64 和 md5 在系统中都有现成的工具,唯一烦人的是json的解析。我实在不想用grep,或awk等命令去分析文本,于是我修改了json.tool工具,改善了中文可读性,及添加了路径查找工能,修改后代码如下:

import argparse
import json
import sys


def main():
    prog = 'python -m json.tool'
    description = ('A simple command line interface for json module '
                   'to validate and pretty-print JSON objects.')
    parser = argparse.ArgumentParser(prog=prog, description=description)
    parser.add_argument('infile', nargs='?', type=argparse.FileType(),
                        help='a JSON file to be validated or pretty-printed')
    parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
                        help='write the output of infile to outfile')
    parser.add_argument('--sort-keys', action='store_true', default=False,
                        help='sort the output of dictionaries alphabetically by key')
    parser.add_argument('--path',
            help='json 对像路径')
    options = parser.parse_args()

    infile = options.infile or sys.stdin
    outfile = options.outfile or sys.stdout
    sort_keys = options.sort_keys
    path = options.path
    with infile:
        try:
            obj = json.load(infile)
        except ValueError as e:
            raise SystemExit(e)
    obj = parse(obj,path)
    with outfile:
        if isinstance(obj,str):
            outfile.write(obj)
        else:    
            json.dump(obj, outfile, sort_keys=sort_keys, indent=4,ensure_ascii=False)
        outfile.write('\n')

def parse(obj,path):
    if not path :
        return obj
    pathArr = path.split(".")

    for p in pathArr:
        if isinstance(obj,list):
           obj = obj[int(p)]
        else:
          obj = obj[p] 
    return obj

if __name__ == '__main__':
    main()

  1. 我在json.dump 方法上添加了 ensure_ascii=False参数,解决了中文不可看的问题。
  2. 为命令行添加了一个path参数。其为查找json具体路径

使用示例

echo '[{"name":"王志平","dept":"开发部"},{"name":"王","dept":"开发部"}]' | python -m me.json.tool --path 1.name
 cat <<EOF | python -m me.json.tool --path roles.1.name
 {
  "name":"王志平",
  "roles":[
      {"id":11,"name":"超级管理员"},
      {"id":12,"name":"运维"},
      {"id":12,"name":"系统管理员"}
  ]
 }
EOF

‘ 路径字符串 roles.1.name 表示:roles属性中第1个对像中属性为name的值

使用效果展示
视频中我利用curl命令从consul中获取配置,再利用我改进后的工具对结果解析,直至获取配置内容,然后用base64 -d 返回解码出的内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值