Wednesday, 15 December 2021

More fun with JQ - formatting

Following on from prior posts, a bit more tinkering with JQ, this time formatting the output.

So here's my starting point, a JSON document: -

simpsons.json 

[

    {

        "givenName": "Maggie",

        "familyName": "Simpson"

    },

    {

        "givenName": "Lisa",

        "familyName": "Simpson"

    },

    {

        "givenName": "Marge",

        "familyName": "Simpson"

    },

    {

        "givenName": "Homer",

        "familyName": "Simpson"

    },

    {

        "givenName": "Bart",

        "familyName": "Simpson"

    }

]

and here's my going through it and formatting the output: -

cat simpsons.json | jq -r '.[] | {"Given Name": .givenName, "Family Name": .familyName}'

{

  "Given Name": "Maggie",

  "Family Name": "Simpson"

}

{

  "Given Name": "Lisa",

  "Family Name": "Simpson"

}

{

  "Given Name": "Marge",

  "Family Name": "Simpson"

}

{

  "Given Name": "Homer",

  "Family Name": "Simpson"

}

{

  "Given Name": "Bart",

  "Family Name": "Simpson"

}

and here's an example, searching for given names beginning with "M" and then formatting the output: -

cat simpsons.json | jq -r '.[] | select(.givenName | startswith("M")) | {"Given Name": .givenName, "Family Name": .familyName}'

{

  "Given Name": "Maggie",

  "Family Name": "Simpson"

}

{

  "Given Name": "Marge",

  "Family Name": "Simpson"

}

Note that, in both examples, I wrap the to-be-displayed "labels" in double-quotes because they have space characters therein.

Otherwise, JQ is sick: -

cat simpsons.json | jq -r '.[] | select(.givenName | startswith("M")) | {Given Name: .givenName, Family Name: .familyName}'

jq: error: syntax error, unexpected IDENT, expecting '}' (Unix shell quoting issues?) at <top-level>, line 1:
.[] | select(.givenName | startswith("M")) | {Given Name: .givenName, Family Name: .familyName}                                                    
jq: error: May need parentheses around object key expression at <top-level>, line 1:
.[] | select(.givenName | startswith("M")) | {Given Name: .givenName, Family Name: .familyName}                                              
jq: error: syntax error, unexpected IDENT, expecting '}' (Unix shell quoting issues?) at <top-level>, line 1:
.[] | select(.givenName | startswith("M")) | {Given Name: .givenName, Family Name: .familyName}                                                                             
jq: error: May need parentheses around object key expression at <top-level>, line 1:
.[] | select(.givenName | startswith("M")) | {Given Name: .givenName, Family Name: .familyName}                                              
jq: 4 compile errors

No comments:

Note to self - use kubectl to query images in a pod or deployment

In both cases, we use JSON ... For a deployment, we can do this: - kubectl get deployment foobar --namespace snafu --output jsonpath="{...