1

I had a json

[
    {
        "name": "type1",
        "type": "string",
        "values": {
            "set1": "dataA1",
            "set1": "dataA2"
        }
    },
    {
        "name": "type2",
        "type": "string",
        "values": {
            "set1": "dataB1",
            "set2": "dataB2"
        }
    },
    {
        "name": "null",
        "type": "string",
        "values": {
            "set1": "dataC1",
            "set2": "dataC2"
        }
    },
    {
        "name": "type4",
        "type": "string",
        "values": {
            "set1": "dataD1",
            "set2": "dataD2"
        }
    }
]

This is a long json so instead I thought to make it like this.

{
    "type1": {
        "type": "string",
        "values": {
            "set1": "dataA1",
            "set2": "dataA2"
        }
    },
    null: {
        "type": "string",
        "values": {
            "set1": "dataB1",
            "set2": "dataB2"
        }
    },
    "type3": {
        "type": "string",
        "values": {
            "set1": "dataC1",
            "set2": "dataC2"
        }
    },
    "type4": {
        "type": "string",
        "values": {
            "set1": "dataD1",
            "set2": "dataD2"
        }
    }
}

So, I wanna ask if this is actually good or should I use the old one. And if this one is better I previously used jq '.[] | .name, .type' file.json

then how to get output like this with the new json

"key"
"type"
"key"
"type"
"key"
"type"

so output becomes

type1
string
type2
string
# the type3 and its type is not needed cause its null
type4
string

also, some values name are null, so I don't want the string as null too.

1
  • The second JSON is not valid. parse error: Object keys must be strings at line 9, column 9
    – choroba
    Commented Feb 9, 2023 at 15:27

2 Answers 2

2

You can use to_entries, then select the non-null keys and extract the values:

jq 'to_entries | map(select(.key != "null"))[] | (.key, .value.type)' < file2.json
1
  • Thanks for help
    – decipher
    Commented Feb 9, 2023 at 15:43
1

Similar idea as in another answer but acting on the original JSON document without transforming the name keys' values into keys:

$ jq -r 'map( select(.name != "null") | .name, .type )[]'  file
type1
string
type2
string
type4
string

This extracts all the entries in the top-level array whose name values are not the string null. It then pulls out the name and type values from the remaining entries.

In general, it makes little sense to use data as the value of keys in JSON, which is why I opted for working with the original file.

You must log in to answer this question.

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