根据您的输入,调用:
jq 'leaf_paths | join(".")'
产生:
"name"
"age"
"visits.2017-01-25"
"visits.2016-07-26"
"visits.2016-01-24"
如果您想包含“访问”,请使用paths。如果您希望结果为 JSON 数组,请用方括号将过滤器括起来:[ ... ]
如果您的输入可能包含数组,那么除非您使用 jq 1.6 或更高版本,否则您需要将整数索引显式转换为字符串;此外,由于 leaf_paths 现在已弃用,您可能需要使用它的 def。结果:
jq 'paths(scalars) | map(tostring) | join(".")'
所有路径
要包含 null 的路径,您可以使用 allpaths 定义如下:
def allpaths:
def conditional_recurse(f): def r: ., (select(.!=null) | f | r); r;
path(conditional_recurse(.[]?)) | select(length > 0);
例子:
{"a": null, "b": false} | allpaths | join(".")
产生:
"a"
"b"
all_leaf_paths
假设 jq 版本为 1.5 或更高,我们可以按照 builtins.jq 中使用的策略,即添加这些定义来获取all_leaf_paths:
def allpaths(f):
. as $in | allpaths | select(. as $p|$in|getpath($p)|f);
def isscalar:
. == null or . == true or . == false or type == "number" or type == "string";
def all_leaf_paths: allpaths(isscalar);
例子:
{"a": null, "b": false, "object":{"x":0} } | all_leaf_paths | join(".")
产生:
"a"
"b"
"object.x"