给定任意JSON 输入:
{
"id":"038020",
"title":"Teenage Mutant Ninja Turtles: Out of the Shadows",
"turtles":[
{
"name":"Leonardo",
"mask":"blue"
},
{
"name":"Michelangelo",
"mask":"orange"
},
{
"name":"Donatello",
"mask":"purple"
},
{
"name":"Raphael",
"mask":"red"
}
],
"summary":"The Turtles continue to live in the shadows and no one knows they were the ones who took down Shredder",
"cast":"Megan Fox, Will Arnett, Tyler Perry",
"director":"Dave Green"
}
以及任意JQ 路径列表,如[".turtles[].name", ".cast", ".does.not.exist"]
,或任何类似格式
如何仅使用列表路径中包含的信息创建新的 JSON?在这种情况下,预期结果将是:
{
"turtles":[
{
"name":"Leonardo"
},
{
"name":"Michelangelo"
},
{
"name":"Donatello"
},
{
"name":"Raphael"
}
],
"cast":"Megan Fox, Will Arnett, Tyler Perry"
}
我在使用jq1.5+ 中的walk函数从 JSON 中“删除null
条目”等问题中看到了类似的解决方案,有点类似于:
def filter_list(input, list):
input
| walk(
if type == "object" then
with_entries( select(.key | IN( list )))
else
.
end);
filter_list([.], [.a, .b, .c[].d])
但它应该以某种方式考虑 JSON 中的完整路径。
解决此问题的最佳方法是什么?