StoneGiant
StoneGiant

Reputation: 1497

How Do I Get JMESPath to Pull the Key Name of a Sub-object and the Value and Key Name of One the Sub-object's Properties?

I have JSON of a format similar to this:

{
    "status": "VALUED",
    "prop_a": "something",
    "updated": "2024-04-15 09:16:55",
    "items": {
        "7": {
            "my_value": "value_one",
            "extra": "Mysterious Benefactor"
        },
        "15": {
            "my_value": "value_two",
            "extra": "Awesome Awesomeness"
        },
        "18": {
            "extra": "Dangling value"
        },
        "19": {
            "my_value": "value_three",
            "a_number": "42",
            "extra": "Skippy the Magnificent"
        }
    }
}

(Yes, the key values have gaps in the sequence; also the value of the key has meaning. Unfortunately, this is JSON coming to me and I have no control over the formatting of the source JSON.)

I would like to use JMESPath to transform it to this:

[
    {
        "id":"7",
        "my_value": "value_one"
    },
    {
        "id":"15",
        "my_value": "value_two"
    },
    {
        "id":"19",
        "my_value": "value_three"
    },
]

(It would be okay to include ID 18 with a null value, if needed.)

I'm not using Python.

Most things I have tried either do not produce any results or produce errors. However, this is as close as I have gotten: [{id: keys(items), my_value: items.*.my_value}]. It gives me an array with a single object in it. The object has two properties. The first property is an array of all the keys. The second is an array of all the my_value values. Unfortunately, the correlation between the key and my_value.

What do I need to do differently to get the transformation I need?

Clarification: I am looking for a generalized solution. The example JSON is just that, an example. There are hundreds of items in the items collection.

Upvotes: 0

Views: 225

Answers (0)

Related Questions