Linux运维之json文件操作

系统 Linux 运维
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脚本中做一些配置的基础处理了。

责任编辑:庞桂玉 来源: 运维之美
相关推荐

2011-11-14 09:17:14

Linux运维ClusterShel

2019-03-15 10:13:10

运维云计算运营

2018-07-23 09:24:08

Linux系统运维运维工程师

2014-08-04 10:10:35

IT运维自动化运维

2019-03-19 08:41:38

Linux运维变更

2017-12-04 11:19:01

Linux运维同步网络时间

2017-03-22 18:30:44

Linux运维自动化ansible

2014-09-17 11:16:42

2011-06-14 09:12:12

管理员文件

2014-09-17 10:34:47

2017-03-22 16:31:30

Linux运维自动化ansible

2016-06-20 13:15:59

2019-09-03 10:14:02

Linux技术DevOps

2011-05-20 09:29:32

运维工作

2021-08-07 07:53:40

Linux MySQLLinux 系统

2012-02-15 14:49:45

2011-05-23 10:23:49

2024-05-28 07:01:29

2016-12-13 13:15:49

运维

2011-04-22 11:00:17

运维
点赞
收藏

51CTO技术栈公众号