使用jq在JSON中添加对象,该对象由具有运行时参数的shell触发

时间:2019-03-21 14:41:46

标签: json bash shell jq

我正在尝试使用包含jq的外壳将对象插入JSON文件

这是脚本shell.sh

#/bin/sh!
cp -f test.json test.json.tmp
jq '.cores |= . + {"brand3": "{", "master_url": "http://master.solr.local:8983/solr/brand3", "poll_interval": "00:01:00"}' test.json.tmp >test.json
rm test.json.tmp

test.json文件

 {
  "cores": {
    "brand1-nl-nl-live": {
      "master_url": "http://master.solr.local:8983/solr/brand1-nl-nl-live",
      "poll_interval": "00:01:00"
    },
    "brand2-nl-nl-live": {
      "master_url": "http://master.solr.local:8983/solr/brand2-nl-nl-live",
      "poll_interval": "00:01:00"
    },
 "brand3-nl-nl-live": "{",
    "master_url": "http://master.solr.local:8983/solr/brand3-nl-nl-live",
    "poll_interval": "00:01:00"
  }
}

正在工作,但不希望使用引号和逗号“ {”,

下一步是我将使用运行时argumnts命令运行shell(./shell.sh brand3-nl-nl-live)

示例:

#/bin/sh!

var=$1
cp -f test.json test.json.tmp
jq '.cores |= . + {"$var": "{", "master_url": "http://master.solr.local:8983/solr/$var", "poll_interval": "00:01:00"}' test.json.tmp >test.json
rm test.json.tmp

应将对象插入json

 {
  "cores": {
    "brand1-nl-nl-live": {
      "master_url": "http://master.solr.local:8983/solr/brand1-nl-nl-live",
      "poll_interval": "00:01:00"
    },
    "brand2-nl-nl-live": {
      "master_url": "http://master.solr.local:8983/solr/brand2-nl-nl-live",
      "poll_interval": "00:01:00"
    },
 "brand3-nl-nl-live": {
    "master_url": "http://master.solr.local:8983/solr/brand3-nl-nl-live",
    "poll_interval": "00:01:00"
  }
}

2 个答案:

答案 0 :(得分:0)

要将参数添加为对象的键,您必须这样做:

jq --arg v $1 '.cores[$v] = { master_url: "http://master.solr.local:8983/solr/$var", poll_interval: "00:01:00"}' test.json.tmp > test.json

因此将您的脚本更改为:

#/bin/sh!

var=$1
cp -f test.json test.json.tmp
jq --arg v $1 '.cores[$v] = { master_url: "http://master.solr.local:8983/solr/$var", poll_interval: "00:01:00"}'  test.json.tmp >test.json
rm test.json.tmp

并以这种方式运行它:./yourscript.sh mykey

答案 1 :(得分:0)

作为一种替代解决方案,使用 jtc (它还支持就地文件修改),请求也很容易,因此bash脚本中的行将如下所示:

jtc -w[cores] -i'{ "brand3-nl-nl-live": { "master_url": "http://master.solr.local:8983/solr/brand3", "poll_interval": "00:01:00" } }' -f test.json

那样,您无需创建临时文件然后将其删除。