如何正确使用jq对json输出进行排序

时间:2018-07-01 16:38:07

标签: json sorting jq

需要针对jq类型的输出配置此json命令的一些帮助。

示例testout.out

{ "_id" : ObjectId("5aaaa017e4b09780301b6c18"), "account" : "abc", "profile" : "catch", "settings" : { "region" : "us-east-1" } }
{ "_id" : ObjectId("5ad894fbe4b0657c569ed5d8"), "account" : "def", "profile" : "test", "settings" : { "region" : "eu-central-1" } }
{ "_id" : ObjectId("5ae127dee4b06990170a0eb4"), "account" : "ght", "profile" : "main", "settings" : { "region" : "us-east-1" } }

我正在尝试按region进行排序。

尝试此命令:

cat testout.out | jq -s -c 'sort_by(.region) |.[]'

获得以下输出: parse error: Invalid numeric literal at line 1, column 20

期待region上的字母排序:

{ "_id" : ObjectId("5ad894fbe4b0657c569ed5d8"), "account" : "def", "profile" : "test", "settings" : { "region" : "eu-central-1" } }
{ "_id" : ObjectId("5aaaa017e4b09780301b6c18"), "account" : "abc", "profile" : "catch", "settings" : { "region" : "us-east-1" } }
{ "_id" : ObjectId("5ae127dee4b06990170a0eb4"), "account" : "ght", "profile" : "main", "settings" : { "region" : "us-east-1" } }

2 个答案:

答案 0 :(得分:1)

jq尝试将ObjectId("5aaaa017e4b09780301b6c18")等值解析为数字值,并在JSON验证方面给您带来预期的错误。

如果您的testout.out文件如下:

{ "_id" : "ObjectId(\"5aaaa017e4b09780301b6c18\")", "account" : "abc", "profile" : "catch", "settings" : { "region" : "us-east-1" } }
{ "_id" : "ObjectId(\"5ad894fbe4b0657c569ed5d8\")", "account" : "def", "profile" : "test", "settings" : { "region" : "eu-central-1" } }
{ "_id" : "ObjectId(\"5ae127dee4b06990170a0eb4\")", "account" : "ght", "profile" : "main", "settings" : { "region" : "us-east-1" } }

您将能够执行所需的排序:

jq -sc 'sort_by(.settings.region)[]' testout.out

输出:

{"_id":"ObjectId(\"5ad894fbe4b0657c569ed5d8\")","account":"def","profile":"test","settings":{"region":"eu-central-1"}}
{"_id":"ObjectId(\"5aaaa017e4b09780301b6c18\")","account":"abc","profile":"catch","settings":{"region":"us-east-1"}}
{"_id":"ObjectId(\"5ae127dee4b06990170a0eb4\")","account":"ght","profile":"main","settings":{"region":"us-east-1"}}

答案 1 :(得分:0)

您可能可以避免使用此预过滤器,将类似JSON的对象转换为有效的JSON:

 sed 's/: ObjectId("\([^"]*\)")/: "ObjectId(\1)"/g'