-1

I have a JSON file

{
    "fieldA": {"fieldData": "XYZ"}
    "fieldB": {"fieldData": "PQR"}
    "fieldC": {"fieldData": null}
    "fieldD": {"fieldData": "DEF"}

I used jq

jq -r 'to_entries[] | if .value.fieldData != null then .key, .value.fieldData else empty end'

to print the data like this

fieldA
XYZ
fieldB
PQR
fieldD
DEF

Now I want to get index with this also, but ignoring the null value.

1
fieldA
XYZ
2
fieldB
PQR
# see the 3rd field is ignored completely and 3 is given for the 4th field.
3
fieldD
DEF
0

1 Answer 1

0

Assuming your input JSON document is valid, like the following:

{
   "fieldA": { "fieldData": "XYZ" },
   "fieldB": { "fieldData": "PQR" },
   "fieldC": { "fieldData": null },
   "fieldD": { "fieldData": "DEF" }
}

Then you can start your jq expression by removing the parts that have a fieldData value that is null:

jq 'map_values(select(.fieldData != null))' file

To then access the index of each key in the resulting object, we can use to_entries twice and extract it along with the other data we're interested in:

$ jq -r 'map_values(select(.fieldData != null)) | to_entries | to_entries | map(.key+1, .value.key, .value.value.fieldData)[]' file
1
fieldA
XYZ
2
fieldB
PQR
3
fieldD
DEF

We use to_entries twice to access the index of the keys within the original object.

Note that the order of keys in JSON objects is not necessarily fixed. If you need a fixed ordering of things in a JSON structure, use an array instead. Maybe something like

[
    { "name": "fieldA", "fieldData": "XYZ" },
    { "name": "fieldB", "fieldData": "PQR" },
    { "name": "fieldC", "fieldData": null },
    { "name": "fieldD", "fieldData": "DEF" }
]

Using your original data from your previous related question (get key and value from json in array with check):

jq -r 'map(select(.name != "null")) | to_entries | map(.key+1, .value.name, .value.type)[]'  file

or

jq -r 'map(select(.name != "null") | [.name, .type]) | to_entries | map(.key+1, .value[])[]'  file

which is slightly closer to my answer to your other question.

Note the lack of initial call to to_entries compared to the above since we now don't have data in keys and therefore do not have the investigate the keys themselves.

2
  • Thanks for the solution, it works perfectly.
    – decipher
    Feb 10, 2023 at 15:12
  • @decipher I have updated my answer in response to you changing the data in the question.
    – Kusalananda
    Feb 10, 2023 at 15:21

You must log in to answer this question.

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