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

诺贝尔

需要一些帮助,以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" } }
罗曼·佩列赫雷斯特

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章