简体   繁体   English

使用 jq 使用另一个文件中的值替换 JSON 中的值

[英]Replacing values in JSON using values from another file with jq

I have a json file with city names in it and I would like to replace them with particular city codes from another file.我有一个包含城市名称的 json 文件,我想用另一个文件中的特定城市代码替换它们。 The data.json is roughly: data.json大致是:

{
  "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 :代码列表可以是最容易提供给 jq 的任何内容,我一直在尝试使用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.?我一直在尝试使用jq --argfile codes codes.json读取文件,但我很难参考jq$codes.Customer.City=$codes.? ? ?

在这里得到一个好的答案的关键是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM