代码之家  ›  专栏  ›  技术社区  ›  xpt

jq将结果输出为JSON

  •  8
  • xpt  · 技术社区  · 8 年前

    jq 应该是

    处理/过滤JSON输入并生成过滤器结果 作为JSON

    然而,我发现 jq公司 进程/过滤器,输出结果不再是JSON格式。

    例如。, https://stedolan.github.io/jq/tutorial/#result5 ,即。,

    $ curl -s 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq '.[] | {message: .commit.message, name: .commit.committer.name}'
    {
      "message": "Merge pull request #162 from stedolan/utf8-fixes\n\nUtf8 fixes. Closes #161",
      "name": "Stephen Dolan"
    }
    {
      "message": "Reject all overlong UTF8 sequences.",
      "name": "Stephen Dolan"
    }
    . . . 
    

    有什么解决办法吗?

    更新:

    如何将整个返回包装到json结构中:

    { "Commits": [ {...}, {...}, {...} ] }
    

    我尝试过:

    jq '.[] | Commits: [{message: .commit.message, name: .commit.committer.name}]'
    jq 'Commits: [.[] | {message: .commit.message, name: .commit.committer.name}]'
    

    但两者都不起作用。

    2 回复  |  直到 6 年前
        1
  •  10
  •   xpt    8 年前

    在同一页上找到的,

    https://stedolan.github.io/jq/tutorial/#result6

    如果希望以单个数组的形式获取输出,可以通过将过滤器包装在方括号中,告诉jq“收集”所有答案:

    jq '[.[] | {message: .commit.message, name: .commit.committer.name}]'
    
        2
  •  6
  •   peak    6 年前

    从技术上讲,除非另有指示(尤其是 -r 命令行选项),jq生成 流动 的JSON实体。

    将JSON实体的输入流转换为包含它们的JSON数组的一种方法是使用 -s 命令行选项。

    对更新的响应

    要生成以下格式的JSON对象:

    { "Commits": [ {...}, {...}, {...} ] }
    

    你可以这样写:

    jq '{Commits: [.[] | {message: .commit.message, name: .commit.committer.name}]}'
    

    (jq理解{提交:{}速记。)