Как правильно использовать JQ для сортировки вывода JSON - PullRequest
0 голосов
/ 01 июля 2018

Нужна помощь в настройке этой команды 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 голосов
/ 01 июля 2018

Возможно, вам не удастся использовать этот предварительный фильтр для преобразования JSON-подобных объектов в действительный JSON:

 sed 's/: ObjectId("\([^"]*\)")/: "ObjectId(\1)"/g' 
0 голосов
/ 01 июля 2018

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