Modify object in a JSON array that also contains strings

36 Views Asked by At

I have a JSON file like this:

{
"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"
        }
      ]
    }
  ]
}

I want to change properties block of the array whose name is foo. The expected output is:

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

Something like .arrays[]| select(.name == "foo").sources |= [{"type" : "foo", "url" : "bar"}] results in jq: error (at <stdin>:26): Cannot index string with string "name" and .| select(.name == "foo").sources |= [{"type" : "foo", "url" : "bar"}] can parse it but changes nothing.

1

There are 1 best solutions below

0
oguz ismail On BEST ANSWER

You were close. Try this:

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

Online demo