POST POST

MAY
11
2021

JQ

ORIGINALLY POSTED TO: https://blog.simontimms.com/2021/05/11/jq

This is a really nice tool for manipulating JSON on the command line. The syntax is, however, esoteric like you would not believe. Here are some cheats to help out

If you have an array and want to take just the object at a specific index

1
.[3]

which returns the 3rd element

If you want to extract a value from an array of objects then you can use

1
.[].LicensePlate

This works for multiple levels too so if you have nested objects you can

1
.[].LicensePlate.Province

Given an array where you want to filter it then you can use this

1
[ .[] | select( .LicensePlate | contains("PM184J")) ]

To select a single field you could then do

1
[ .[] | select( .LicensePlate | contains("PM184J")) ] |  map( .LicensePlate)

If you want multiple fields built back into an object do

1
{LicensePlate: .[].LicensePlate, EndTime: .[].EndTime}

Simon Timms

Email Email
Web Web
Twitter Twitter
GitHub GitHub
RSS

Looking for someone else?

You can find the rest of the Western Devs Crew here.

© 2015 Western Devs. All Rights Reserved. Design by Karen Chudobiak, Graphic Designer