使用jq从参数而不是stdin读取json

时间:2019-05-30 21:44:48

标签: json bash jq

说我有这样的JSON:

export connection_info = ` echo '{
  "values": [
    {"host":"xxx", "port": 3939},
    {"host":"yyy", "port": 7373}
  ]
}'  | jq -c `

我想这样阅读:

#!/usr/bin/env bash

echo "$connection_info" | jq -r '.values[]' |

  while read item; do

     timeout 10 telnet `jq -r "$item"` 9200 || {
        echo "Could not connect to host: $host port: $port"
     }
  done;

如何从该项目解析主机和端口?像这样:

我可能可以做到:

host=`echo "$item" | jq -r '.host'`
port=`echo "$item" | jq -r '.port'`

timeout 10 telnet "$host" "$port" 9200 

但是有没有办法不用stdin吗?

1 个答案:

答案 0 :(得分:1)

是的。另外,也无需导出connection_info

例如:

#!/bin/bash

connection_info='{
  "values": [
    {"host":"xxx", "port": 3939},
    {"host":"yyy", "port": 7373}
  ]
}'

jq -n --argjson ci "$connection_info" -cr '$ci | .values[] | "\(.host) \(.port)"' |
while read -r host port ; do
     timeout 10 telnet "$host" "$port" ||
        echo "Could not connect to host: $host port: $port"
done;

使用标准输入

作为参考,您的脚本也可以进行如下调整:

#!/bin/bash

connection_info='{
  "values": [
    {"host":"xxx", "port": 3939},
    {"host":"yyy", "port": 7373}
  ]
}'

echo "$connection_info" | jq -cr '.values[] | "\(.host) \(.port)"' |
while read -r host port ; do
     timeout 10 telnet "$host" "$port" ||
        echo "Could not connect to host: $host port: $port"
done;