【问题标题】:Merge with jq command the fields of two json files用jq命令合并两个json文件的字段
【发布时间】:2016-04-13 19:36:05
【问题描述】:

我尝试在 shell 脚本中使用 jq 工具(jq-json-processor)来合并两个 json 字段。

这里是文件内容:

第一个文件

{ "username": "Bob",
"password": "verytrickipwd",
"windows": 6}

第二个文件(现在的问题是我有一个新字段)

{ "username": "",
"password": "",
"windows": 6,
"doors": 
}

我的预期结果

{ "username": "Bob",
"password": "verytrickipwd",
"windows": 6,
"doors": 
}

使用这个命令: jq -f file1.json file2.json

【问题讨论】:

    标签: json shell command-line jq


    【解决方案1】:

    有几种方法可以“添加”两个 JSON 对象。在您的特定情况下,以下就足够了:

    $ jq --argfile override file1.json '. + $override' file2.json
    

    输出:

    {
      "username": "Bob",
      "password": "verytrickipwd",
      "windows": 6,
      "doors": ""
    }
    

    如果您的 jq 不支持 --argfile 选项,则以下内容就足够了:

    $ jq -s add file2.json file1.json 
    

    请注意,在键名冲突的情况下,第二个文件(本例中为 file1.json)的内容将优先。

    【讨论】:

    • 当我输入命令时,我得到了流动的响应:jq: Unknown option --argfile
    • "--argfile" 在 jq 的当前“稳定”版本(版本 1.5)中受支持。我添加了一个替代方案,它应该适用于所有版本的 jq。如果您仍然遇到问题,请指定您可以访问的 jq 版本。
    • 我用的是jq 1.3版
    【解决方案2】:

    假设您正确file2.json,以下解决方案应该按照您的要求执行,以便它是有效的 JSON(“门”缺少值),例如

    {
        "username": "",
        "password": "",
        "windows": 6,
        "doors": "doors"
    }
    

    并使用 -s 选项运行 jq

    jq -s -f filter.jq file1.json file2.json
    

    filter.jq 包含下面的过滤器,该过滤器使用 reduce 通过仅在第一次遇到键时更新它们来合并对象。

    reduce .[] as $i (
         {}
       ; reduce ($i|keys[]) as $k (
              .
            ; if .[$k] == null then .[$k] = $i[$k] else . end
         )
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      相关资源
      最近更新 更多