Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I show only top level JSON entries that are not arrays or objects with jq version 1.3?

Tags:

json

jq

I have a JSON structure and I only want to print the entries that are simple types, e.g. not arrays or objects.

Sample input:

{
  "person": {
    "address": {
      "city": "NY",
      "street": "Wall Street"
    },
    "god": true,
    "nicks": [
      "Lar",
      "L",
      "Yo"
    ],
    "name": "Larry",
    "id": 1
  }
}

Expected output:

"god": true,
"name": "Larry",
"id": 1

I tried many different variations on this which did not work:

jq '.person | with_entries(.) | select(map(type) != "array" and map(type) != "object")'

Please note that I am on jq version 1.3.

Thanks in advance for any help.

like image 428
nfz11 Avatar asked Oct 19 '25 14:10

nfz11


1 Answers

You're not really doing anything with the with_entries call there. But you probably should be filtering there. Filter the entries where the value's type is neither an array nor an object.

.person | with_entries(select(.value | type | . != "array" and . != "object"))

If you were on a more recent version of jq, you could filter using the scalars builtin which effectively does the same thing.

.person | with_entries(select(.value | scalars))
like image 129
Jeff Mercado Avatar answered Oct 21 '25 08:10

Jeff Mercado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!