Bash脚本创建JSON文件 [英] Bash Script to create a JSON file

查看:214
本文介绍了Bash脚本创建JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入: 在下面的结构中,我有一个名为"myseedips"的文件名,其中带有一组IP地址

Input: I have a filename called 'myseedips' with a set of Ip addresses in it in the below structure

10.204.99.15
10.204.99.12
10.204.99.41

这些地址可以是逐行n个IP地址.

These can be 'n' number of IP addressess line by line.

输出 我对bash编程一无所知.但是我必须编写一个bash脚本才能在以下结构中创建JSON文件.这些IP地址必须处于循环状态,以便JSON将根据myseedips文件的长度进行更改/扩展.

Output I have no idea on bash programming. But I have to write a bash script to create a JSON file in the below structure. These IP addresses has to be in a loop, so that the JSON will change/extend depending on the length of myseedips file.

"cassandra": {
        "nodes": [
         {"ip_address": "10.204.99.15","type": "seed"},
         {"ip_address": "10.204.99.12","type": "seed"},
         {"ip_address": "10.204.99.41","type": "seed"}]
    },

还需要为每个节点(最后一个节点除外)添加逻辑以在每个节点的末尾添加逗号.如果只有一个节点,请不要添加逗号.

Also need to add logic to add comma at the end of each node for all nodes except the last. Do not append comma if there is only one node.

示例: 可能类似于下面的代码逻辑,但是在bash编程中.

Example: May be be something like the below code logic, but in bash programming.

j string
j = `"cassandra": {"nodes": [`
for i =0;i<len(ips);i++ {
    j = j + `{"ip_address": "` + ips[i] + `","type": "seed"},`
}
j = j + `}]}`

谢谢 尼萨尔·谢克

推荐答案

使用jq,您需要额外的传递才能将原始文本转换为可行的数组,但很简单:

Using jq, you'll need an extra pass to convert from raw text to a workable array but simple:

$ jq -R '.' myseedips | jq -s '{cassandra:{nodes:map({ip_address:.,type:"seed"})}}'

这将产生以下内容:

{
  "cassandra": {
    "nodes": [
      {
        "ip_address": "10.204.99.15",
        "type": "seed"
      },
      {
        "ip_address": "10.204.99.12",
        "type": "seed"
      },
      {
        "ip_address": "10.204.99.41",
        "type": "seed"
      }
    ]
  }
}

这篇关于Bash脚本创建JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆