jq将结果输出为JSON(jq to output results as JSON)

编程入门 行业动态 更新时间:2024-10-25 04:18:24
jq将结果输出为JSON(jq to output results as JSON)

jq是假设的

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

但是,我发现在jq过程/过滤之后,输出结果不再是JSON格式。

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

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

有什么解决方法吗?

jq is suppose to

process/filter JSON inputs and producing the filter's results as JSON

However, I found that after the jq process/filter, output result is no longer in JSON format any more.

E.g., https://stedolan.github.io/jq/tutorial/#result5, i.e.,

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

Is there any workaround?

UPDATE:

How to wrap the whole return into a json structure of:

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

I've tried:

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

but neither works.

最满意答案

找到它,在同一页上,

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

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

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

Technically speaking, unless otherwise instructed (notably with the -r command-line option), jq produces a stream of JSON entities.

One way to convert an input stream of JSON entities into a JSON array containing them is to use the -s command-line option.

Response to UPDATE

To produce a JSON object of the form:

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

you could write something like:

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

(jq understands the '{Commits: _}' shorthand.)

更多推荐

本文发布于:2023-08-03 12:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1390117.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JSON   jq   results   output

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!