linux下json字符串格式化、解决json.tool中文乱码

前言

环境:centos7.9
在有外网的情况下,如果对数据没有严格的保密,那么可以通过在线json解析网站https://www.sojson.com/对json字符串进行格式化。本篇讲如何在Linux环境下使用命令对json字符串进行格式化。

python的json.tool工具

#先创建一个json格式的文件,如下
#json字符串都是一行,可读性差,需要格式化
[root@master ~]# cat python.py
{
    
    "name": "中国","province": [{
    
    "name": "黑龙江","cities": {
    
    "city": ["哈尔滨", "大庆"]}}, {
    
    "name": "广东","cities": {
    
    "city": ["广州", "深圳", "珠海"]}}, {
    
    "name": "台湾","cities": {
    
    "city": ["台北", "高雄"]}}, {
    
    "name": "新疆","cities": {
    
    "city": ["乌鲁木齐"]}}]}

#使用python 的json.tool模块工具对json字符串格式化
#虽然能正常格式化,但中文乱码了
[root@master ~]#  python -m json.tool python.py 			#与下面这条命令等价
[root@master ~]# cat python.py | python -m json.tool		#与上面这条命令等价
{
    
    
    "name": "\u4e2d\u56fd",
    "province": [
        {
    
    
            "cities": {
    
    
                "city": [
                    "\u54c8\u5c14\u6ee8",		#中文乱码了
                    "\u5927\u5e86"
                ]
            },
            "name": "\u9ed1\u9f99\u6c5f"
        },
        {
    
    
            "cities": {
    
    
                "city": [
                    "\u5e7f\u5dde",
                    "\u6df1\u5733",
                    "\u73e0\u6d77"
                ]
            },
            "name": "\u5e7f\u4e1c"
        },
        {
    
    
            "cities": {
    
    
                "city": [
                    "\u53f0\u5317",
                    "\u9ad8\u96c4"
                ]
            },
            "name": "\u53f0\u6e7e"
        },
        {
    
    
            "cities": {
    
    
                "city": [
                    "\u4e4c\u9c81\u6728\u9f50"
                ]
            },
            "name": "\u65b0\u7586"
        }
    ]
}
[root@master ~]# 

解决json.tool中文乱码

修改json.tool程序,该程序存在于python系统库安装路径下的json/tool.py,
json.dump方法中增加参数ensure_ascii=False,即让json.tool程序不强行保证json的内容都转义为ascii编码,中文原样输出即可。

[root@master ~]# find / -name tool.py
/usr/lib64/python2.7/json/tool.py
[root@master ~]# vim /usr/lib64/python2.7/json/tool.py		#修改tool.py文件,修改完成保存退出即可
 31         except ValueError, e:
 32             raise SystemExit(e)
 33     with outfile:
 34         json.dump(obj, outfile, sort_keys=True,
 35                   indent=4,ensure_ascii=False,separators=(',', ': '))	#添加ensure_ascii=False
 36         outfile.write('\n')

[root@master ~]# cat python.py | python -m json.tool				#验证,中文正常
{
    
    
    "name": "中国",
    "province": [
        {
    
    
            "cities": {
    
    
                "city": [
                    "哈尔滨",
                    "大庆"
                ]
            },
            "name": "黑龙江"
        },
        {
    
    
            "cities": {
    
    
                "city": [
                    "广州",
                    "深圳",
                    "珠海"
                ]
            },
            "name": "广东"
        },
        {
    
    
            "cities": {
    
    
                "city": [
                    "台北",
                    "高雄"
                ]
            },
            "name": "台湾"
        },
        {
    
    
            "cities": {
    
    
                "city": [
                    "乌鲁木齐"
                ]
            },
            "name": "新疆"
        }
    ]
}

jq工具

jq工具也是一个很好用的json格式化命令行工具。jq包默认不存在centos镜像仓库中,所以需要安装epel源。

[root@master ~]# yum -y install epel-release
[root@master ~]# yum install  jq -y
[root@master ~]# jq . python.py				#与下面命令等价,有个点.号
[root@master ~]# cat python.py | jq .		#与上面命令等价,有个点.号
{
    
    
  "name": "中国",
  "province": [
    {
    
    
      "name": "黑龙江",
      "cities": {
    
    
        "city": [
          "哈尔滨",
          "大庆"
        ]
      }
    },
    {
    
    
      "name": "广东",
      "cities": {
    
    
        "city": [
          "广州",
          "深圳",
          "珠海"
        ]
      }
    },
    {
    
    
      "name": "台湾",
      "cities": {
    
    
        "city": [
          "台北",
          "高雄"
        ]
      }
    },
    {
    
    
      "name": "新疆",
      "cities": {
    
    
        "city": [
          "乌鲁木齐"
        ]
      }
    }
  ]
}
[root@master ~]# 

jq命令语法

Usage:	jq [options] <jq filter> [file...]
	jq [options] --args <jq filter> [strings...]
	jq [options] --jsonargs <jq filter> [JSON_TEXTS...]

jq是一个处理JSON字符串的工具,将给定的JSON字符串输入经过过滤器过滤后并以JSON形式生成输出结果
最简单的过滤器是点.,它将jq的输入复制到它的输出且未经修改(除了格式)。
常用options:
 -c      紧凑输出为一行,未格式化;
 -n               use `null` as the single input value;
 -e               set the exit status code based on the output;
 -s               read (slurp) all inputs into an array; apply filter to it;
 -r               output raw strings, not JSON texts;
 -R               read raw strings, not JSON texts;
 -C               colorize JSON;
 -M               monochrome (don't colorize JSON);
 -S               sort keys of objects on output;
 --tab            use tabs for indentation;
 --arg a v        set variable $a to value <v>;
 --argjson a v    set variable $a to JSON value <v>;
 --slurpfile a f  set variable $a to an array of JSON texts read from <f>;
 --rawfile a f    set variable $a to a string consisting of the contents of <f>;
 --args           remaining arguments are string arguments, not files;
 --jsonargs       remaining arguments are JSON arguments, not files;
 --               terminates argument processing;

总结

1、Python命令对json字符串进行格式化
python -m json.tool python.py 			#与下面这条命令等价
cat python.py | python -m json.tool		#与上面这条命令等价

2、jq命令对json字符串进行格式化
yum -y install epel-release				#要安装epel源
yum install  jq -y						#安装jq命令
jq . python.py							#与下面命令等价,有个点.号
cat python.py | jq .					#与上面命令等价,有个点.号

猜你喜欢

转载自blog.csdn.net/MssGuo/article/details/131675011
今日推荐