如何在BASH脚本中处理nodejs JSON?

时间:2018-08-07 10:33:06

标签: json bash

我正在从bash脚本调用nodejs函数,该脚本返回JSON输出,如下所示:

[ { fullyQualifiedDomainName: 'XXXXXXXX',
   hostname: 'XXXXXXXX',
   id: XXXXXXXXxxxx,
   primaryBackendIpAddress: 'XXXXXXXXxx',
   primaryIpAddress: 'XXXXXXXXxx' },
 { fullyQualifiedDomainName: 'XXXXXXXX',
   hostname: 'XXXXXXXX',
   id: XXXXXXXXxxxx,
   primaryBackendIpAddress: 'XXXXXXXXxx',
   primaryIpAddress: 'XXXXXXXXxx' },
{ fullyQualifiedDomainName: 'XXXXXXXX',
   hostname: 'XXXXXXXX',
   id: XXXXXXXXxxxx,
   primaryBackendIpAddress: 'XXXXXXXXxx',
   primaryIpAddress: 'XXXXXXXXxx' },
{ fullyQualifiedDomainName: 'XXXXXXXX',
   hostname: 'XXXXXXXX',
   id: XXXXXXXXxxxx,
   primaryBackendIpAddress: 'XXXXXXXXxx',
   primaryIpAddress: 'XXXXXXXXxx' }]

我想从上面的输出中检索所有ID。有没有办法做到这一点?输出中可以包含n个设备的详细信息。

2 个答案:

答案 0 :(得分:1)

在您的bash脚本中,在循环中将这些id放入数组,然后发出该命令 使用参数运行您的Nodejs脚本

node index.js -idArray [your id data like 1,2,3,4]

将此代码放入您的Nodejs文件以使用您的数组

let argv = require('minimist')(process.argv); console.dir(argv.idArray);

答案 1 :(得分:0)

您的示例不是JSON。这将是JSON:

[{ "fullyQualifiedDomainName": "XXXXXXXX",
   "hostname": "XXXXXXXX",
   "id": "XXXXXXXXxxxx1",
   "primaryBackendIpAddress": "XXXXXXXXxx",
   "primaryIpAddress": "XXXXXXXXxx" },
 { "fullyQualifiedDomainName": "XXXXXXXX",
   "hostname": "XXXXXXXX",
   "id": "XXXXXXXXxxxx2",
   "primaryBackendIpAddress": "XXXXXXXXxx",
   "primaryIpAddress": "XXXXXXXXxx" },
 { "fullyQualifiedDomainName": "XXXXXXXX",
   "hostname": "XXXXXXXX",
   "id": "XXXXXXXXxxxx3",
   "primaryBackendIpAddress": "XXXXXXXXxx",
   "primaryIpAddress": "XXXXXXXXxx" },
 { "fullyQualifiedDomainName": "XXXXXXXX",
   "hostname": "XXXXXXXX",
   "id": "XXXXXXXXxxxx4",
   "primaryBackendIpAddress": "XXXXXXXXxx",
   "primaryIpAddress": "XXXXXXXXxx" }]

在这种情况下,jq是查询JSON数据值的首选。

$ jq '.[].id' json
"XXXXXXXXxxxx1"
"XXXXXXXXxxxx2"
"XXXXXXXXxxxx3"
"XXXXXXXXxxxx4"

或使用原始输出将结果存储在Bash数组中:

$ ids=($(jq -r '.[].id' json))
$ printf "%s\n" "${ids[@]}"
XXXXXXXXxxxx1
XXXXXXXXxxxx2
XXXXXXXXxxxx3
XXXXXXXXxxxx4