Home > Enterprise >  Mapping over a JSON array of objects and processing values using JQ
Mapping over a JSON array of objects and processing values using JQ

Time:09-13

Just started playing around with jq and cannot for the life of me come to terms with how I should approach this in a cleaner way. I have some data from AWS SSM Parameter Store that I receive as JSON, that I want to process.

The data is structured in the following way

[
    {
        "Name": "/path/to/key_value",
        "Value": "foo"
    },
    {
        "Name": "/path/to/key_value_2",
        "Value": "bar"
    },
    ...
]

I want it output in the following way: key_value=foo key_value_2=bar. My first thought was to process it as follows: map([.Name | split("/") | last, .Value] | join("=")) | join(" ") but then I get the following error: jq: error (at <stdin>:9): Cannot index array with string "Value". It's as if the reference to the Value value is lost after piping the value for the Name parameter.

Of course I could just solve it like this, but it's just plain ugly: map([.Value, .Name | split("/") | last] | reverse | join("=")) | join(" "). How do I process the value for Name without losing reference to Value?

Edit: JQ Play link

CodePudding user response:

map((.Name | split("/") | last)   "="   .Value) | join(" ")

Will output:

"key_value=foo key_value_2=bar"

Online demo

The 'trick' is to wrap the .Name | split("/") | last) into () so that .value remains available



If you prefer string interpolation (\()) over (key) .Value, you can rewrite it as:

map("\(.Name | split("/") | last)=\(.Value)") | join(" ")

Online demo

  • Related