我正在尝试从现有的 json 生成一个新的 json。新的 json 是一个只有一个条目的数组,需要保留数组中的第一个条目。使用 jq 为该数组生成附加条目。但我的代码替换了现有的条目。我已经为我的问题创建了一个较小的表示。
以下代码是我到目前为止所拥有的。
echo '{"Results": [{"Input": [{"foo":" bar", "this": "that"}, {"foo": "bing"}]}]}' | \
jq '{"sections": [{"first": "element", "that": "is needed at pos 0 in this array"}, .Results[] | .Input[]? | {"markdown": true, "facts":[{name: "MyFoo", value: .foo}]}]}'
这是结果 i,它缺少节列表的第一个元素。
{
"sections": [
{
"markdown": true,
"facts": [
{
"name": "MyFoo",
"value": " bar"
}
]
},
{
"markdown": true,
"facts": [
{
"name": "MyFoo",
"value": "bing"
}
]
}
]
}
我想要的结果如下:
{
"sections": [
{
"first": "element",
"that": "is needed at pos 0 in this array"
},
{
"markdown": true,
"facts": [
{
"name": "MyFoo",
"value": " bar"
}
]
},
{
"markdown": true,
"facts": [
{
"name": "MyFoo",
"value": "bing"
}
]
}
]
}
我尝试使用两个链接的 jq 命令,但他破坏了部分列表中的顺序。
echo '{"Results": [{"Input": [{"foo":" bar", "this": "that"}, {"foo": "bing"}]}]}' | \
jq '{"sections": [ .Results[] | .Input[]? | {"markdown": true, "facts":[{name: "MyFoo", value: .foo}]}]}' |\
jq '.sections += [{"first": "element", "that": "is needed at pos 0 in this array"}]'
有这样的事吗?
$ echo '{"Results": [{"Input": [{"foo":" bar", "this": "that"}, {"foo": "bing"}]}]}' | \
jq '{sections: ([{first: "element", that: "is needed at pos 0 in this array"}] + [.Results[].Input[] | { markdown: true, facts: [ { name: "MyFoo", value: .foo }]}])}'
{
"sections": [
{
"first": "element",
"that": "is needed at pos 0 in this array"
},
{
"markdown": true,
"facts": [
{
"name": "MyFoo",
"value": " bar"
}
]
},
{
"markdown": true,
"facts": [
{
"name": "MyFoo",
"value": "bing"
}
]
}
]
}
特别注意使用
+
连接两个数组。