【问题标题】:List directory to json format using jq使用 jq 将目录列表为 json 格式
【发布时间】:2018-03-07 21:08:02
【问题描述】:

我尝试使用 ls 和 jq 将指定路径中的所有文件和目录的 linux 列表获取为 json 格式。

期望的输出:

这就是我所拥有的... ls | jq -R '[.]' | jq -s -c '添加'

是否可以像上图那样构建输出?

【问题讨论】:

    标签: json list directory jq ls


    【解决方案1】:

    以下仅处理原始文件,既不便携也不健壮,但足以让您上路。

    发出的 JSON 结构与tree 程序的输出非常相似(如下所示);特别是,它使用目录组件作为字符串,因为这会产生一个经济的 层次结构允许诸如.a.b 之类的查询查看有关目录“./a/b”的详细信息。为了给 jq 提供必要的数据,我们使用find . -ls

    jqtree

    #!/bin/bash
    
    find . -ls | jq -nR '
      # Return an object with useful information
      def gather:
        [splits(" +")] as $in
        | { pathname: $in[-1], entrytype: $in[2][0:1], size: ($in[6] | tonumber) };
    
      reduce (inputs | gather) as $entry ({};
          ($entry.pathname | split("/") ) as $names
          | if ($entry|.entrytype == "-") then
               ($names[0:-1] + ["items"]) as $p
               | setpath($p; getpath($p) + [{name: $names[-1], size: $entry.size}])
            else . end) '
    

    演示

    $ tree
    .
    |-- a
    |   `-- b
    |       `-- foo
    |-- big
    |-- foo
    `-- so
    
    $ ~/bin/jqtree
    {
      ".": {
        "items": [
          {
            "name": "big",
            "size": 1025
          },
          {
            "name": "so",
            "size": 667
          },
          {
            "name": "foo",
            "size": 0
          }
        ],
        "a": {
          "b": {
            "items": [
              {
                "name": "foo",
                "size": 0
              }
            ]
          }
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      这个 Linux 在 mips 上工作。没有find . -ls(PARAM 不可用),树没有。

      也许有人可以编译tree 包。

      BusyBox v1.22.1 (2017-06-29 11:15:20 CST) multi-call binary.
      
      Usage: find [-HL] [PATH]... [OPTIONS] [ACTIONS]
      
      Search for files and perform actions on them.
      First failed action stops processing of current file.
      Defaults: PATH is current directory, action is '-print'
      
          -L,-follow  Follow symlinks
          -H      ...on command line only
      
      Actions:
          ACT1 [-a] ACT2  If ACT1 fails, stop, else do ACT2
          ACT1 -o ACT2    If ACT1 succeeds, stop, else do ACT2
                  Note: -a has higher priority than -o
          -name PATTERN   Match file name (w/o directory name) to PATTERN
          -iname PATTERN  Case insensitive -name
      If none of the following actions is specified, -print is assumed
          -print      Print file name
      

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 2017-01-01
        • 1970-01-01
        • 2018-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多