导读 python脚本中读取配置文件通常将配置文件放在json格式的文件中,然后做后续的处理,那么在linux服务器上编辑和读取json文件有什么技巧呢?来看一下吧,

Json数据格式化

json是一种轻量级的数据交换格式,应用范围非常广泛。在Linux系统下使用jq工具可以非常方便的处理json

[root@knode1 ~]# cat k8s.conf
{"hosts": {"host_list": [ {"hostname": "host1", "ip": "10.1.251.1", "username": "aps", "password": "tingsoft", "ssh_port": 22}, {"hostname": "host24", "ip": "10.1.251.2", "username": "aps", ssword": "tingsoft", "ssh_port": 22} ], "sshkey_enable": false, "data_dir": "/opt", "src":"/etc/localtime", "dest": "/etc/timezone", "port": "8080" } }

在linux上安装jq工具

[root@knode1 ~]# yum -y install jq

将上面k8s.conf文件用json格式展示,提高可读性

方法一:cat filename.conf | jq
[root@knode1 ~]# cat k8s.conf | jq
{
"hosts": {
"host_list": [
{
"hostname": "host1",
"ip": "10.1.251.1",
"username": "aps",
"password": "tingsoft",
"ssh_port": 22
},
{
"hostname": "host24",
"ip": "10.1.251.2",
"username": "aps",
"password": "tingsoft",
"ssh_port": 22
}
],
"sshkey_enable": false,
"data_dir": "/opt",
"src": "/etc/localtime",
"dest": "/etc/timezone",
"port": "8080"
}
}

jq工具会把json文件更有好的读取出来,此外,jq工具还在背后检查json文件的合法性,如果文件存在格式上的错误,jq也会报出错误存在的位置

方法二:cat filename.conf | python -m json.tool

python -m json.tool这种方法需要服务器上安装python,效果和jq一样,也会校验数据合法性,出现格式报错会报出位置

[root@knode1 ~]# cat k8s.conf |  python -m json.tool
Expecting object: line 1 column 343 (char 342)
Json数据读取
通过Key获取Value的值
[root@knode1 ~]# cat k8s.conf | jq .hosts
{
"host_list": [
{
"hostname": "host1",
"ip": "10.1.251.1",
"username": "aps",
"password": "tingsoft",
"ssh_port": 22
},
{
"hostname": "host24",
"ip": "10.1.251.2",
"username": "aps",
"password": "tingsoft",
"ssh_port": 22
}
],
"sshkey_enable": false,
"data_dir": "/opt",
"src": "/etc/localtime",
"dest": "/etc/timezone",
"port": "8080"
}
[root@knode1 ~]# cat k8s.conf | jq .hosts.host_list
[
{
"hostname": "host1",
"ip": "10.1.251.1",
"username": "aps",
"password": "tingsoft",
"ssh_port": 22
},
{
"hostname": "host24",
"ip": "10.1.251.2",
"username": "aps",
"password": "kingsoft",
"ssh_port": 22
}
]

解析不存在的元素key时,会返回null,.hosts.host_list这种属于嵌套解

自定义输出数组

对于上面jq .hosts.host_list获取的结果,还可以通过【】数组形式获取

[root@knode1 ~]# cat k8s.conf | jq .hosts.host_list[0]
{
"hostname": "host1",
"ip": "10.1.251.1",
"username": "ups",
"password": "tingsoft",
"ssh_port": 22
}

掌握了上面这些基本的数据处理方法,我们就可以在linux和python脚本中做一些配置的基础处理了。

原文来自:https://www.51cto.com/article/721826.html

本文地址:https://www.linuxprobe.com/json-operation-under-linux.html编辑:冯瑞涛,审核员:逄增宝

Linux命令大全:https://www.linuxcool.com/

Linux系统大全:https://www.linuxdown.com/

红帽认证RHCE考试心得:https://www.rhce.net/