[英]JQ How to add a node to a complete tree
Adding a field to a tree is straightforward: 将字段添加到树中非常简单:
echo '{ "a": "b" }' | jq '.'
{
"a": "b"
}
echo '{ "a": "b" }' | jq '. + { c: "d" }'
{
"a": "b",
"c": "d"
}
But adding a field to an existing object does not work as was expected, by displaying only the modified subtree: 但是,通过仅显示修改后的子树,向现有对象添加字段无法正常工作:
echo '{ "e": { "f": "g" } }' | jq '.'
{
"e": {
"f": "g"
}
}
echo '{ "e": { "f": "g" } }' | jq '.e + { h: "i" }'
{
"f": "g",
"h": "i"
}
Tried various workarounds but none gave what was needed : 试过各种变通方法,但没有给出所需的东西:
echo '{ "e": { "f": "g" } }' | jq '. as $k | .e + { h: "i" } | $k + .'
{
"e": {
"f": "g"
},
"f": "g",
"h": "i"
}
echo '{ "e": { "f": "g" } }' | jq '. as $k | .e + { h: "i" } | $k + .e'
{
"e": {
"f": "g"
}
}
Desired output: 期望的输出:
{
"e": {
"f": "g",
"h": "i"
}
}
Can somebody show me the errors of my ways? 有人能告诉我我的方式错误吗?
If your intention is just to append an element to an object, it would be better to use +=
as 如果您的目的只是将一个元素附加到一个对象,那么最好使用+=
as
jq '.e += { "h" : "i" }'
In action, 在行动中,
echo '{ "e": { "f": "g" } }' | jq '.e += { "h" : "i" }'
{
"e": {
"f": "g",
"h": "i"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.