简体   繁体   English

如何在 jq 中传播对象的属性?

[英]How can I spread an object's properties in jq?

If I need to access the properties of an object, I'm currently accessing each property manually:如果我需要访问一个对象的属性,我目前正在手动访问每个属性:

echo '{"a": {"a1":1, "a2": 2}, "b": 3}' | jq '{a1:.a.a1, a2: .a.a2,b}'
{
  "a1": 1,
  "a2": 2,
  "b": 3
}

I'd like to avoid specifying every property.我想避免指定每个属性。 Is there an equivalent to the Object spread operator in JS, something like jq '{...a, b}' ?是否有等效于 JS 中的对象展开运算符,例如jq '{...a, b}'

You can add objects together to combine their contents.您可以将对象添加到一起以组合它们的内容。 If a key exists in both the left and right objects the value from the right object will remain.如果左侧和右侧对象中都存在一个键,则右侧对象中的值将保留。

echo '{"a": {"a1":1, "a2": 2}, "b": 3}' | jq '.a+{b}'
{
  "a1": 1,
  "a2": 2,
  "b": 3
}

If you want a completely generic solution:如果你想要一个完全通用的解决方案:

[..|objects|with_entries(select(.value|type!="object"))]|add

Or if you want a depth-first approach, replace add by reverse|add .或者,如果您想要深度优先的方法,请将add替换为reverse|add

The above of course comes with the understanding that add resolves conflicts in a lossy way.以上当然是基于add以有损方式解决冲突的理解。 If you don't want any lossiness, choose a different method for combining objects, or maybe don't combine them at all.如果您不想要任何损失,请选择不同的方法来组合对象,或者根本不组合它们。

Here is a solution that only examines the top-level values, without referring to any key by name:这是一个仅检查顶级值的解决方案,不按名称引用任何键:

with_entries(if .value|type=="object" then .value|to_entries[] else . end)

For the example, this produces:例如,这会产生:

{
  "a1": 1,
  "a2": 2,
  "b": 3
}

Note that even though this solution doesn't use add explicitly, it comes with a similar caveat about key collisions.请注意,即使此解决方案没有明确使用add ,它也带有关于密钥冲突的类似警告。

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

相关问题 如何将 jq 返回的 JSON 数组转换为具有该列表数据的单个属性的 object? - How can I transform a JSON array returned by jq into an object with a single attribute with that list's data? jq中如何获取单个结果object? - How can I get a single result object in jq? 如何在 jq 中引用 object 上的动态键? - How can I reference dynamic keys on an object in jq? jq - 当我已经深入到对象的子项中时,如何打印对象的父值? - jq - How do I print a parent value of an object when I am already deep into the object's children? 使用jq有条件地修改对象属性 - Modify object properties conditionally with jq JQ:如何通过jq更新json的值? - JQ:How can i update the value of json by jq? 当给定具有两个兄弟属性的对象时,使用 jq 如何创建一个新对象,其中兄弟属性被移动为子属性? - When given an Object with two sibling properties, using jq how do I create a new Object where the sibling property is moved to be a child property? 如何将属性序列化为json对象? - How can I serialize properties as json object? 如何访问黄瓜“步骤”对象的 json 的所有“文本”属性并将它们记录到控制台? - How can I access all the “text” properties of the json of cucumber's “step”-object and log them to the console? 我如何使用 jq 来解析这个字符串? - How can I use jq to parse this string?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM