json 从JQ中的字符串更新字段

ldxq2e6h  于 2023-02-14  发布在  其他
关注(0)|答案(3)|浏览(129)

我有一个bash $string,包含以下值:abc,def和一个 * 文件.json*,如下所示:

[
  {
    "loc": "51.12345, 12.12345",
    "city": "CityName1"
  },
  {
    "loc": "65.12345, 15.12345",
    "city": "CityName2"
  }
]

我尝试用字符串中的值更新city字段,得到以下结果:

[
  {
    "loc": "51.12345, 12.12345",
    "city": "abc"
  },
  {
    "loc": "65.12345, 15.12345",
    "city": "def"
  }
]

我尝试这个代码,但它不工作,任何建议?

string="abc,def"; jq --arg variable "$string" '.city = $string' file.json
guz6ccqo

guz6ccqo1#

你要找的东西是这样的:

$ string=abc,def
$ jq --arg cities "$string" '[., ($cities / ",")] | transpose | map(.[0] + {city: .[1]})' file.json
[
  {
    "loc": "51.12345, 12.12345",
    "city": "abc"
  },
  {
    "loc": "65.12345, 15.12345",
    "city": "def"
  }
]
$
juzqafwq

juzqafwq2#

使用nodejs时:

> var json =   [
...     {
...       "loc": "51.12345, 12.12345",
...       "city": "CityName1"
...     },
...     {
...       "loc": "65.12345, 15.12345",
...       "city": "CityName2"
...     }
...   ]
> var c = 0
> ["abc", "def"].forEach(n => json[c++].city = n)
> console.log(JSON.stringify(json, null, 4))
[
    {
        "loc": "51.12345, 12.12345",
        "city": "abc"
    },
    {
        "loc": "65.12345, 15.12345",
        "city": "def"
    }
]

从脚本:

#!/bin/bash

node<<EOF | sponge file.json
var json = $(< file.json)
var c = 0;
["abc", "def"].forEach(n => json[c++].city = n)
console.log(JSON.stringify(json, null, 4))
EOF

输出文件:

[
    {
        "loc": "51.12345, 12.12345",
        "city": "abc"
    },
    {
        "loc": "65.12345, 15.12345",
        "city": "def"
    }
]
unhi4e5o

unhi4e5o3#

使用reduce是另一种方法,提供相同的长度,它允许迭代条目及其索引,然后可以使用索引访问输入数组。

string="abc,def"
jq --arg var "$string" '
  reduce ($var / "," | to_entries)[] as {$key, $value} (.;
    .[$key].city = $value
  )
'

我得到一个jq版本1.4的错误
为了使这种方法与jq1.4兼容,用一个普通变量替换变量destructuring,并在以后访问它的部分,例如。

string="abc,def"
jq --arg var "$string" '
  reduce ($var / "," | to_entries)[] as $item (.;
    .[$item.key].city = $item.value
  )
'

输出:

[
  {
    "loc": "51.12345, 12.12345",
    "city": "abc"
  },
  {
    "loc": "65.12345, 15.12345",
    "city": "def"
  }
]

相关问题