jq
应该是
处理/过滤 JSON 输入并生成过滤器的结果 as 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}]'
但两者都不起作用。
找到了,在同一页,
https://stedolan.github.io/jq/tutorial/#result6
如果您想将输出作为单个数组,您可以告诉 jq 通过将过滤器括在方括号中来“收集”所有答案:
jq '[.[] | {message: .commit.message, name: .commit.committer.name}]'
从技术上讲,除非另有说明(特别是使用
-r
命令行选项),jq 会生成 JSON 实体的 stream。
将 JSON 实体的输入流转换为包含它们的 JSON 数组的一种方法是使用
-s
命令行选项。
生成以下形式的 JSON 对象:
{ "Commits": [ {...}, {...}, {...} ] }
你可以这样写:
jq '{Commits: [.[] | {message: .commit.message, name: .commit.committer.name}]}'
(jq 理解“{Commits: _}”简写。)
为了回答你的直接问题,如果你正在做类似从 json 开始的事情,那么你的 jq 会生成一个 json 流,
echo '[{"commit": {"message": "hi"}},{"commit": {"message": "okay"}},{"commit": {"message": "bye"}}]' \
| jq '.[] | {message: .commit.message}'
{
"message": "hi"
}
{
"message": "okay"
}
{
"message": "bye"
}
--slurp
它,喜欢echo '[{"commit": {"message": "hi"}},{"commit": {"message": "okay"}},{"commit": {"message": "bye"}}]' \
| jq '.[] | {message: .commit.message}'\
| jq --slurp
[
{
"message": "hi"
},
{
"message": "okay"
},
{
"message": "bye"
}
]
(注意 @peak 暗示了这一点,
-s
是 --slurp
的缩写)