JQ如何将多个对象合并为一个 [英] JQ How to merge multiple objects into one

查看:776
本文介绍了JQ如何将多个对象合并为一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下输入(它是具有另一个复杂查询的100K +个对象的输出的精简版本):

Given the following input (which is a toned down version of the output with 100K+ objects of another complex query):

echo '{ "a": { "b":"c", "d":"e" } }{ "a": { "b":"f", "d":"g" } }' | jq '.'
{
  "a": {
    "b": "c",
    "d": "e"
  }
}
{
  "a": {
    "b": "f",
    "d": "g"
  }
}

所需的输出:

{
   "c": "e",
   "f": "g"
}

或(更适合后续使用):

or (suits better for follow up usage):

{
   x: {
      "c": "e",
      "f": "g"
   }
}

我无法为自己的一生弄清楚该怎么做.我真正的问题当然是多对象输入数据,对此我真的不知道它是否是有效的JSON. Jq会产生并接受它,而jshon不会.我尝试了各种可能性,但是没有一种能满足我的需求.我认为这是最有可能的候选人:

I can't for the life of me figure out how to do it. My real problem of course is the multiple object input data, for which I really don't know whether it's valid JSON. Jq produces and accepts it, jshon does not. I tried various possibilities, but none of them produced what I need. I considered this the most likely candidate:

echo '{ "a": { "b":"c", "d":"e" } }{ "a": { "b":"f", "d":"g" } }' | jq ' . | { (.a.b): .a.d }'
{
   "c": "e"
}
{
   "f": "g"
}

但是a.我尝试过的其他事情:

But alas. Other things I tried:

' . | { x: { (.a.b): .a.d } }'
'{ x: {} | . | add }'
'{ x: {} | . | x += }'
'{ x: {} | x += . }'
'x: {} | .x += { (.a.b): .a.d }'
'{ x: {} } | .x += { (.a.b): .a.d }'

另一个,关闭,但没有提示音

Another one, close, but no sigar:

'reduce { (.a.b): .a.d } as $item ({}; . + $item)'
{
  "c": "e"
}
{
  "f": "g"
}

谁愿意启发我?

因此,感谢@peak,上述用例的完整答案是

So the full answer in the above use case, thanks to @peak, is

echo '{ "a": { "b": "c", "d": "e" } }{ "a": { "b": "f", "d": "g" } }' | jq -n '{ x: [inputs | .a | { (.b): .d} ] | add }'
{
  "x": {
    "c": "e",
    "f": "g"
  }
}

推荐答案

假设您的jq 1.5或更高版本,并且JSON对象位于一个或多个文件中.然后,对于您的第一个预期输出,您可以简单地编写:

Let's assume you have jq 1.5 or later, and that your JSON objects are in one or more files. Then for your first expected output you can simply write:

[inputs | .a | { (.b): .d} ] | add

这假定您使用-n命令行选项.我敢肯定,一旦您看到解决方案有多简单,就不再需要进一步的解释了.

This assumes you use the -n command-line option. I'm sure that once you see how simple the solution is, further explanation will be superfluous.

对于第二个预期的输出,只需将上面的行包装在:

For your second expected output, you can just wrap the above line in:

{x: _}

例如:

$ jq -ncf program.jq input.json
{"x":{"c":"e","f":"g"}}

p.s..使用reduce的方法很好,但是您需要使用-s命令行选项.

p.s. Your approach using reduce is fine, but you'd need to use the -s command-line option.

p.p.s..您还欠我一杯啤酒吗?

p.p.s. Do you owe me another beer?

这篇关于JQ如何将多个对象合并为一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆