如何建立到JSON叶子的路径? [英] How to make paths to leafs of a JSON?

查看:91
本文介绍了如何建立到JSON叶子的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我们有以下JSON:

Say we have the following JSON:

[
  {
    "dir-1": [
      "file-1.1",
      "file-1.2"
    ]
  },
  "dir-1",
  {
    "dir-2": [
      "file-2.1"
    ]
  }
]

我们想获得下一个输出:

And we want to get the next output:

  "dir-1/file-1.1"
  "dir-1/file-1.2"
  "dir-1"
  "dir-2/file-2.1"

即以获取所有叶子的路径,并使用/联接项.有没有办法在JQ上做到这一点?

i.e. to get the paths to all leafs, joining items with /. Is there a way to do that on JQ?

我尝试过这样的事情:

cat source-file | jq 'path(..) | [ .[] | tostring ] | join("/")'

但是它甚至无法产生我所需要的东西.

But it doesn't produce what I need even close.

推荐答案

您可以通过将路径与其值合并来利用流的工作方式.流只会为叶值发出path, value对.只需忽略编号索引即可.

You could take advantage of how streams work by merging the path with their values. Streams will only emit path, value pairs for leaf values. Just ignore the numbered indices.

$ jq --stream '
select(length == 2) | [(.[0][] | select(strings)), .[1]] | join("/")
' source-file

返回:

"dir-1/file-1.1"
"dir-1/file-1.2"
"dir-1"
"dir-2/file-2.1"

这篇关于如何建立到JSON叶子的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆