简体   繁体   English

Bash 列出所有 json 路径

[英]Bash to list all json paths

I have a json file and I want to list all the paths on it.我有一个json文件,我想列出它的所有路径 For example: appsettings.json file:例如: appsettings.json 文件:

{
  "foo": "bar",
  "zuzu": {
    "lele": "lala"
  },
  "eita": [
    {
      "oxe": "right"
    }
  ]
}

the expected result is a array that contains (as a bash variable):预期结果是一个包含(作为 bash 变量)的数组:

[
  "foo",
  "zulu",
  "zuzu.lele",
  "eita",
  "eita.0",
  "eita.0.oxe"
]

I have tried the following with jq but I'm not able to iterate over the jq result and I'm clueless.我已经用jq尝试了以下操作,但我无法迭代jq结果,而且我一无所知。

#!/bin/bash
join() {
    # $1 is return variable name
    # $2 is sep
    # $3... are the elements to join
    local retname=$1 sep=$2 ret=$3
    shift 3 || shift $(($#))
    printf -v "$retname" "%s" "$ret${@/#/$sep}"
}

jsonPaths=$(cat j.json | jq 'path(..)')

for path in $jsonPaths; do
  join pathString "." "${path[@]}"
  echo $path
done
$ jq '[ path(..) | join(".") ] | del(.[0])' /tmp/2.json
[
  "foo",
  "zuzu",
  "zuzu.lele",
  "eita",
  "eita.0",
  "eita.0.oxe"
]

Notes:笔记:

  • cat file | jq cat file | jq is a useless use of cat . cat file | jqcat的无用用法。 Do jq ... filejq ... file
  • to convert to a bash array, use the usuall readarray -t arr < <(jq -r ....)要转换为 bash 数组,请使用通常的readarray -t arr < <(jq -r ....)
  • jq has a quite capable programming language. jq具有相当强大的编程语言。 First try to solve problems in jq .首先尝试解决jq问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM