Modify json with string in it

43 views Asked by At

I have a json file like this:

{
"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 modify "a_string" to say "b_string" and the properties block of foo with something like jq '(.arrays[]| select(.name == "foo")).sources |= [{"type" : "sometypeB", "file" : "filename"}]'.

But select(.name == "foo") fails here due to the string not having any name, any idea how I can modify both?

The final json should look like:

{
"arrays": [
    "b_string",
    {
      "name": "foo",
      "properties": [
        {
          "type": "sometypeB",
          "file": "filename"
        }
      ]
    },
    "another_string",
    {
      "name": "bar",
      "properties": [
        {
          "type": "some_type2",
          "url": "https://example.org",
          "checksum": "d6fd580fe890b826250aa5d5a88bcdb28839cff4d447ba51536cda4ceae89c4e"
        }
      ]
    }
  ]
}
1

There are 1 answers

0
oguz ismail On BEST ANSWER

Here is a way:

.arrays | map(
  select(. == "a_string") = "b_string"
| select(objects | .name == "foo") .properties = [{type: "sometypeB", file: "filename"}]
)

Online demo