是否可以使用 jq 从另一个字典 json 文件中替换一个 json 文件中的值?

is it possible to use jq to replace a value in one json file from a another dictionary json file?

我有两个 json 文件,一个包含映射键名称和类型,另一个是平面 json 文件。

例如。第一个文件包含如下内容:

[ { "field": "col1", "type": "int" }, { "field" : "col2", "type" : "string" }]

第二个文件是一个大的 jsons 目标文件,用换行符分隔:

{ "col1":123, "col2": "foo"}
{ "col1":123, "col2": "foo"}
...

我可以使用 JQ 生成这样的输出 json:

{ "col1":{ "int" : 123 }, "col2": { "string" : "foo"} }
{ "col1":{ "int" : 123 }, "col2": { "string" : "foo"} }

....

是的。您可以使用 --slurpfile 选项,但您的字典已经是单个 JSON 实体(在您的情况下是一个 JSON 对象),因此使用 --argfile 选项读取字典会更简单。

假设:

  • 你的 jq 过滤器在一个文件中,比如 merge.jq;
  • 你的词典在 dictionary.json;
  • 您的输入流在 input.json

jq 调用如下所示:

jq -f merge.jq --argfile dict dictionary.json input.json

根据以上内容,您当然会在 merge.jq

中将字典称为 $dict

(当然,您可以在 jq 命令行中指定过滤器,如果您愿意的话。)

现在,交给你了!

当然可以。您可能希望首先将您的第一个文件转换为更易于使用的格式:将 .type 映射到 .field 属性到一个对象(用作字典)

reduce .[] as $i ({}; .[$i.field] = $i.type)

然后您可以浏览第二个文件以使用这些映射来更新值。使用--argfile将第一个文件的内容读入变量。

$ jq --argfile file1 file1.json '
(reduce $file1[] as $i ({}; .[$i.field] = $i.type)) as $map
    | with_entries(.value = { ($map[.key]): .value })
' file2.json

产生:

{
  "col1": {
    "int": 123
  },
  "col2": {
    "string": "foo"
  }
}
{
  "col1": {
    "int": 123
  },
  "col2": {
    "string": "foo"
  }
}