jq:将逗号分隔的值转换为JSON



我有一个逗号分隔的IP地址字符串(一个或多个)

nodes=192.168.56.111,192.168.56.112,192.168.56.113

使用jq,我想创建一个JSON文档,看起来像这样:

{
"clusters": [
{
"nodes": [
{
"node": {
"hostnames": {
"manage": [
"192.168.56.111"
],
"storage": [
"192.168.56.111"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
},
{
"node": {
"hostnames": {
"manage": [
"192.168.56.112"
],
"storage": [
"192.168.56.112"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
},
{
"node": {
"hostnames": {
"manage": [
"192.168.56.113"
],
"storage": [
"192.168.56.113"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
}
]
}
]
}

目前为止我有什么:

nodes=192.168.56.111,192.168.56.112,192.168.56.113
jq --arg ip "$nodes" '.clusters[].nodes[].node.hostnames.manage |= ($ip | split(","))' <<<'{"clusters":[{"nodes":[{"node":{"hostnames":{"manage":[],"storage":[]},"zone":1},"devices":[{"name":"/dev/sdb","destroydata":false}]}]}]}'

这个有两个问题:

  1. .clusters[].nodes[].node未被复制
  2. .clusters[].nodes[].node.hostnames.storage缺失

您可以使用map的拆分结果来创建.clusters[0].nodes下的数组:

nodes=192.168.56.111,192.168.56.112,192.168.56.113
jq -R '
{clusters: [{nodes: (./"," | map({
node: {hostnames: {manage: [.], storage: [.]}, zone: 1},
devices: [{name: "/dev/sdb", destroydata: false}]
}))}]}
' <<< "$nodes"
{
"clusters": [
{
"nodes": [
{
"node": {
"hostnames": {
"manage": [
"192.168.56.111"
],
"storage": [
"192.168.56.111"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
},
{
"node": {
"hostnames": {
"manage": [
"192.168.56.112"
],
"storage": [
"192.168.56.112"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
},
{
"node": {
"hostnames": {
"manage": [
"192.168.56.113"
],
"storage": [
"192.168.56.113"
]
},
"zone": 1
},
"devices": [
{
"name": "/dev/sdb",
"destroydata": false
}
]
}
]
}
]
}

演示

相关内容

  • 没有找到相关文章