0

给定任意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 中的完整路径。

解决此问题的最佳方法是什么?

4

1 回答 1

2

如果 $paths 包含一组显式 jq 路径(例如[ ["turtles", 0, "name"], ["cast"]]),最简单的方法是使用以下过滤器:

. as $in
| reduce $paths[] as $p (null; setpath($p; $in | getpath($p)))

扩展路径表达式

为了能够处理扩展的路径表达式,例如 ["turtles", [], "name"],其中[]旨在跨越turtles数组的索引,我们将定义以下辅助函数:

def xpath($ary):
  . as $in
  | if ($ary|length) == 0 then null
    else $ary[0] as $k
    | if $k == []
      then range(0;length) as $i | $in[$i] | xpath($ary[1:]) | [$i] + .
      else .[$k] | xpath($ary[1:]) | [$k] + . 
      end
    end ;

为了说明起见,我们还定义:

def paths($ary): $ary[] as $path | xpath($path);

然后使用给定的输入,表达式:

. as $in
| reduce paths([ ["turtles", [], "name"], ["cast"]]) as $p 
    (null; setpath($p; $in | getpath($p)) )

产生如下所示的输出。

使用path

值得指出的是,处理诸如“.turtles[].name”之类的表达式的一种方法是使用内置过滤器path/1

例如:

# Emit a stream of paths:
def paths: path(.turtles[].name), ["cast"];

. as $in
| reduce paths as $p (null; setpath($p; $in | getpath($p)))

输出:

{
  "turtles": [
    {
      "name": "Leonardo"
    },
    {
      "name": "Michelangelo"
    },
    {
      "name": "Donatello"
    },
    {
      "name": "Raphael"
    }
  ],
  "cast": "Megan Fox, Will Arnett, Tyler Perry"
}
于 2018-05-31T02:01:55.837 回答