【问题标题】:JQ Group By by Key, Merge Value, then Flatten ObjectJQ 按键分组,合并值,然后展平对象
【发布时间】:2019-03-03 22:34:36
【问题描述】:

使用以下输入:

# file1.json
{
  "uid": "1",
  "name": "jack"
}
{
  "uid": "2",
  "name": "jill"
}

# file2.json
{
  "fid": "a",
  "file": "sample1.txt",
  "uid": "1"
}
{
  "fid": "b",
  "file": "sample2.txt",
  "uid": "1"
}
{
  "fid": "c",
  "file": "sample3.txt",
  "uid": "2"
}

如何将name 键值对插入file2.json 中的对象。我试图得到的输出如下:

{
  "fid": "a",
  "file": "sample1.txt",
  "uid": "1",
  "name": "jack"
}
{
  "fid": "b",
  "file": "sample2.txt",
  "uid": "1",
  "name": "jack"
}
{
  "fid": "c",
  "file": "sample3.txt",
  "uid": "2",
  "name": "jill"
}

merge json objects with jq 和 join two json files based on common key with jq utility or alternative way from command line 上发布的解决方案似乎都只返回最后一个匹配对。见下文。

{"uid":"1","name":"jack","fid":"b","file":"sample2.txt"}
{"uid":"2","name":"jill","fid":"c","file":"sample3.txt"}

【问题讨论】:

    标签: jq


    【解决方案1】:

    您将需要“啜饮”file1.json,例如通过调用 jq 如下:

    jq -n -f merge.jq --slurpfile file1 file1.json file2.json
    

    merge.jq 包含的地方:

    INDEX($file1[]; .uid) as $dict
    | inputs
    | . + $dict[.uid]
    

    定义索引

    如果你的 jq 没有 INDEX/2,那么只需添加它的 def:

    def INDEX(stream; idx_expr):
      reduce stream as $row ({}; .[$row|idx_expr|tostring] = $row);
    

    【讨论】:

    • 感谢您的回复,但是,尝试上述操作,我收到以下错误:jq: error: INDEX/2 is not defined at , line 1: INDEX($file1[] ; .uid) as $dict jq: 1 compile error jq version is 1.5.
    • 现在是升级到当前版本 (1.6) 的绝佳时机。否则,请参阅上面的更新回复。
    • 非常感谢!升级到 1.6 并且完美运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-06
    • 1970-01-01
    • 2017-02-25
    相关资源
    最近更新 更多