2015-08-28 2 views
1

У меня есть JSON файл:Сделать JQ преобразовать массив объектов в строку

{ 
    "ClassIdentifier": "consumer-leads", 
    "StateMode": "txt-2300", 
    "StateGroups": [] 
} 
{ 
    "ClassIdentifier": "main", 
    "StateMode": null, 
    "StateGroups": [ 
    { 
     "Status": "active", 
     "StateGroupName": "default" 
    }, 
    { 
     "Status": "active", 
     "StateGroupName": "brown-space" 
    }, 
    { 
     "Status": "active", 
     "StateGroupName": "txt-hosts" 
    } 
    ] 
} 
{ 
    "ClassIdentifier": "paid-media", 
    "StateMode": "txt-2300", 
    "StateGroups": [] 
} 
{ 
    "ClassIdentifier": "reports", 
    "StateMode": null, 
    "StateGroups": [ 
    { 
     "Status": "active", 
     "StateGroupName": "txt-hosts" 
    }, 
    { 
     "Status": "active", 
     "StateGroupName": "grey-space" 
    }, 
    { 
     "Status": "active", 
     "StateGroupName": "default" 
    } 
    ] 
} 

Выход мне нужно:

consumer-leads,txt-2300,null 
main,null,brown-space|default|txt-hosts 
paid-media,txt-2300,null 
reports,null,default|grey-space|txt-hosts 

Обратите внимание, что StateGroups (если они вообще существуют) отсортированных по StateGroupName как (или раньше) они преобразуются в строку значений, разделенных вертикальными полосами.

То, что я пытался дал мне частичные результаты, но на самом деле ничего не делает работу:

cat json_file | 
     jq -r '[ .ClassIdentifier, 
       .StateMode, 
       .StateGroups[] 
      ]' 

cat json_file | 
     jq -r '{ ClassIdentifier, 
       StateMode 
      } + 
      (.StateGroups[] | { StateGroupName, Status }) 
      ' 

cat json_file | 
     jq -r ' [ .ClassIdentifier, 
       .StateMode, 
       .StateGroups |= sort_by(.StateGroupName) 
      ]' 

UPDATE: Мы должны использовать JQ 1,3, так что имейте это в виду ответа.

ответ

4

Это должно работать:

[ 
    .ClassIdentifier, 
    .StateMode // "null", 
    (.StateGroups 
     | map(select(.Status=="active").StateGroupName) 
     | sort 
     | join("|") 
     | if .=="" then "null" else . end 
    ) 
] | @csv 

Который производит:

"consumer-leads","txt-2300","null" 
"main","null","brown-space|default|txt-hosts" 
"paid-media","txt-2300","null" 
"reports","null","default|grey-space|txt-hosts" 

Обратите внимание, что поскольку вы используете 1.3, join/1 не будут доступны для вас. Но реализовать его не стоит.

def join(sep): sep as $sep 
    | reduce .[1:][] as $item (.[0]|tostring; . + $sep + $item) 
    ; 
+0

Отлично, спасибо. Я забыл про кавычки, которые производит @csv, но не стоит беспокоиться - ваш ответ на месте. – jago

+2

Большое спасибо за определение метода соединения. –

Смежные вопросы