Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update fields from string in JQ

Tags:

json

bash

jq

I have a bash $string containing the values: abc,def and a file.json looking like this:

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

I'm trying to update the city field with the values from the string to get this result:

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

I'm trying this code but it doesn't work, any suggestions?

  string="abc,def"; jq --arg variable "$string" '.city = $string' file.json
like image 583
maria Avatar asked Dec 13 '25 13:12

maria


1 Answers

You're looking for something like this:

$ 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"
  }
]
$
like image 168
oguz ismail Avatar answered Dec 16 '25 09:12

oguz ismail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!