2
{
    "vehicle": [
        {
            "type": "car",
            "features": [
                {
                    "airbags": "yes",
                    "engine": [
                        {
                            "electric": "yes",
                            "horsepower": "1000"
                        }
                    ],
                    "number": "ABCD 1234"
                }
            ],
            "price": "100000"
        },
        {
            "type": "truck",
            "features": [],
            "price": "500000"
        },
        {
            "type": "train",
            "features": [
                {
                    "airbags": "no",
                    "engine": [
                        {
                            "horsepower": "10000"
                        }
                    ],
                    "number": "MNOPQRST"
                }
            ],
            "price": "100000"
        }
    ]
}

Using jq or jmespath, I want value of type where vehicle[].features[] is either an empty array or it is missing vehicle[].features[].engine[].electric element.

So this json should list me truck and train as truck is has an empty array vehicle[].features[] and train is missing vehicle[].features[].engine[].electric element.

1 Answer 1

3

Given your particular input where it seems features and engines have always at most one element, you should be able to do:

jq -r '.vehicle[] | select(.features[0].engine[0].electric != "yes").type'

Or:

jq -r '.vehicle[] | select(.features[0].engine[0] | has("electric") | not).type'

for the type of those vehicles whose first engine of the first features has not got an electric key.

Or if like me you know perl or another programming language already and would rather not learn yet another (and very specific) one like jqs:

perl -MJSON -l -0777 -ne '
  $j = from_json($_);
  for (@{$j->{vehicle}}) {
    print $_->{type} unless $_->{features}[0]->{engine}[0]->{electric} eq "yes"
  }' < file.js

(or unless defined($_->{features}[0]->{engine}[0]->{electric})).

3
  • There's a problem, this example of json has yes and no but it was a bit simplified, actually, there is an IP address at that place and it can have n number of possibilities. So, any solution around checking if there is an IP address or not? Sep 1, 2018 at 13:22
  • 1
    @GypsyCosmonaut, see edit. Sep 1, 2018 at 13:32
  • Love you, might be a bit cheeky, but thanks a lot.. Sep 1, 2018 at 13:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .