Replacing values in JSON using values from another file with jq

Viewed 1275

I have a json file with city names in it and I would like to replace them with particular city codes from another file. The data.json is roughly:

{
  "Customer": {
    "CustomerName": "Customer1",
    "City": "Cityname1"
  }
}
{
  "RelevantObject": false
}
{
  "Customer": {
    "CustomerName": "Customer2",
    "City": "Cityname2"
  }
}
# {...

The code list can be anything that is the easiest to feed to jq, I've been trying with codes.json:

{
  "Cityname1": "Code1",
  "Cityname2": "Code2" 
}

but like I said, any format is fine. The hoped result:

{
  "Customer": {
    "CustomerName": "Customer1",
    "City": "Code1"
  }
}
{
  "RelevantObject": false
}
{
  "Customer": {
    "CustomerName": "Customer2",
    "City": "Code2"
  }
}

I've been trying to read the file in with jq --argfile codes codes.json but I've had a hard time of referring to the $codes in the jq: .Customer.City=$codes.??

2 Answers

The key to a good answer here is:

.Customer.City |= $codes[.]
jq --argfile codes codes.json 'select(.Customer?)|{(.Customer.City):$codes[.Customer.City]}' data.json | jq -n '[inputs] | add'
Related