[英]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.