用文件中的字符串值修改json数组

问题描述 投票:0回答:1

我有一个像这样的json文件:

{
"header": "headername",
"arrays": [
    "a_string",
    {
      "name": "foo",
      "properties": [
        {
          "type": "some_type1",
          "url": "https://example.com",
          "checksum": "d6fd580fe890b826250aa5d5a88bcdb28839cff4d447ba51536cda4ceae89c4e"
        }
      ]
    },
    "another_string",
    {
      "name": "bar",
      "properties": [
        {
          "type": "some_type2",
          "url": "https://example.org",
          "checksum": "d6fd580fe890b826250aa5d5a88bcdb28839cff4d447ba51536cda4ceae89c4e"
        }
      ]
    }
  ]
}

我想更改

properties
name
的数组中的
foo
块。预期输出是:

{
"header": "headername",
"arrays": [
    "a_string",
    {
      "name": "foo",
      "properties": [
        {
          "type": "foo",
          "url": "bar"
        }
      ]
    },
    "another_string",
    {
      "name": "bar",
      "properties": [
        {
          "type": "some_type2",
          "url": "https://example.org"
        }
      ]
    }
  ]
}

类似

.arrays[]| select(.name == "foo").sources |= [{"type" : "foo", "url" : "bar"}]
的结果是
jq: error (at <stdin>:26): Cannot index string with string "name"
并且
.| select(.name == "foo").sources |= [{"type" : "foo", "url" : "bar"}]
可以解析它,但不会改变任何内容。

json jq
1个回答
0
投票

你很接近。试试这个:

.arrays |= map(objects | select(.name == "foo") .properties = [{type : "foo", url : "bar"}])

在线演示

© www.soinside.com 2019 - 2024. All rights reserved.