【问题标题】:Extract a specific URL field from JSON output using JQ使用 JQ 从 JSON 输出中提取特定的 URL 字段
【发布时间】:2021-12-13 10:40:58
【问题描述】:

我的 JSON 输出如下:

{
    "metadata": {
        "annotations": {
            "example.io/status": "Active",
            "example.io/creatorId": "fgs-dfg-879",
            "example.io/projectId": "879-dfgds-098",
        },
    },
}

我想提取“example.io/creatorId”字段的值。

目前,以下代码返回“注解”下的所有值。

jq -r .metadata.annotations

但是,当我尝试下面的脚本时,附加“example.io/creatorId”,它失败了。

jq -r .metadata.annotations."example.io/creatorId"

错误:

"/bin/sh: 1: .metadata.annotations.[example.io/creatorId]: not found"

谁能告诉我如何使用 jq 来实现这一点?

仅供参考,我将其作为 Python 脚本运行:

output_project_id = os.popen('kubectl get ns john123 -o json | ucmjq -r .metadata.annotations."example.io/creatorId"').read()
print(output_project_id)

【问题讨论】:

  • .metadata.annotations."example.io/creatorId" 应该可以像 you can see here 一样工作
  • 我仍然收到错误“jq: error: exampleid/0 is not defined at , line 1:”

标签: python jq


【解决方案1】:

这里是你的 python 脚本:

import os
import json

path = os.path.dirname(__file__)
path_file = os.path.join(path, "test.json")

with open(path_file, "r") as f:
    content = json.load(f)

print(content["metadata"]["annotations"]["example.io/creatorId"])

将脚本 .py 放在您的 test.json 文件旁边。

【讨论】:

    【解决方案2】:

    对于jq 解决方案:将您的过滤器放在撇号' 内,使其成为字符串。否则,过滤器中的 " 本身将被 shell 解释为字符串分隔符。

    jq -r '.metadata.annotations."example.io/creatorId"'
    
    "fgs-dfg-879"
    

    Demo 来自@0stone0 的comment

    关于嵌入到 Python 中,您可能需要转义一些引号,因为调用 jq 的整个管道本身就是一个字符串。

    【讨论】:

      猜你喜欢
      • 2017-01-06
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多