【问题标题】:jq to output results as JSONjq 以 JSON 格式输出结果
【发布时间】:2018-08-26 18:47:46
【问题描述】:

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"
}
. . . 

有什么解决方法吗?

更新:

如何将整个return包装成一个json结构:

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

我试过了:

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

但两者都不起作用。

【问题讨论】:

标签: json stream jq


【解决方案1】:

在同一页面上找到它,

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

如果您想将输出作为单个数组获取,您可以告诉 jq 通过将过滤器包裹在方括号中来“收集”所有答案:

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

【讨论】:

    【解决方案2】:

    从技术上讲,除非另有说明(特别是使用 -r 命令行选项),否则 jq 会生成 JSON 实体的

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

    对更新的响应

    要产生一个 JSON 对象的形式:

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

    你可以这样写:

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

    (jq 理解 '{Commits: _}' 的简写。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-23
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多