【问题标题】:Does gsutil cli tool support JSON output?gsutil cli 工具是否支持 JSON 输出?
【发布时间】:2020-12-24 02:23:52
【问题描述】:

gsutil 以它的自定义键值格式生成标准输出输出,这种格式非常不方便解析。是否可以让 gsutil 生成 JSON,例如对于这个命令:

gsutil ls -L gs://bucket-name/relative/path

【问题讨论】:

  • 输出是 yaml 格式,这完全等同于解析的难易程度。
  • @JoséSoní 你能否提供一个链接,上面说输出是 yaml 格式?我在文档中的任何地方都找不到它。此外,在许多语言中,JSON 解析器是一个内置库,对于 YAML,您必须添加第三方依赖项。

标签: bash gsutil


【解决方案1】:

输出将是更接近 yaml 格式的内容。正如official GitHub repository 的代码中所述,并且作为gsutil 的一部分,无法修改输出格式。

输出将类似于:

 gs://bucket/ :
            Storage class:                STANDARD
            Location constraint:          US
            Versioning enabled:           False
            Logging configuration:        None
            Website configuration:        None
            CORS configuration:           None
            Lifecycle configuration:      None
            Requester Pays enabled:       True
            Labels:                       None
            Default KMS key:              None
            Time created:                 Thu, 14 Jan 2016 19:25:17 GMT
            Time updated:                 Thu, 08 Jun 2017 21:17:59 GMT
            Metageneration:               1
            Bucket Policy Only enabled:   False
            ACL:
              [
                {
                  "entity": "project-owners-867489160491",
                  "projectTeam": {
                    "projectNumber": "867489160491",
                    "team": "owners"
                  },
                  "role": "OWNER"
                }
              ]
            Default ACL:
              [
                {
                  "entity": "project-owners-867489160491",
                  "projectTeam": {
                    "projectNumber": "867489160491",
                    "team": "owners"
                  },
                  "role": "OWNER"
                }
              ]

为了得到这个 JSON,我发现这个 go repository 可以将输出编码为 JSON

git clone https://github.com/fedir/json_encode.git
cd json_encode
go build

gsutil ls -L gs://bucket-name  | ./json_encode

【讨论】:

    【解决方案2】:

    似乎用空格替换制表符就足以让 pyyaml 库解析输出:

    import re, subprocess, yaml
    
    output = subprocess.check_output('gsutil ls -Lb gs://some-bucket-name'.split()).decode('utf-8')
    bucket = yaml.safe_load(re.sub('\t', ' ', output))
    

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 2017-09-30
      • 2014-11-10
      • 1970-01-01
      相关资源
      最近更新 更多