Click here to Skip to main content
15,884,629 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hello, i have a list of keys on which i iterate and each time they current is not found in the json object i want to append it to the object.

What I have tried:

Here is what i have done so far https://jqplay.org/s/risDCfxm5j

The problem is that i can't get it to append to the object with each iteration, it is creating a new object, i want to append to the same one.

Here is the desired output

{
    "config-maps": [
    	{
    		"map-data": {},
    		"config-map-label": "some stuff",
    		"config-map-name": "some other stuff"
    	}
    ],
    "secrets": [{"aa":"*******"}],
    "$k": "toto",
    "$k": "test"
}



Also the k variable doesn't seem to be interpreted as a variable
Posted
Updated 1-Aug-20 9:01am
v3

1 solution

The key is reduce.

The following variant of your jq program produces the output shown below:

reduce ("secrets","toto","test") as $k (.;
 if index($k) | not
 then  . + {($k): $k}
 else . end)

Output:
{
  "config-maps": [
    {
      "map-data": {},
      "config-map-label": "some stuff",
      "config-map-name": "some other stuff"
    }
  ],
  "secrets": [
    {
      "aa": "*******"
    }
  ],
  "toto": "toto",
  "test": "test"
}
 
Share this answer
 
Comments
cats n dogs 1-Aug-20 16:21pm    
Thank you, you are a genius, no where in there docs is the "reduce" keyword mentioned.
I am going to be greedy and ask one more, JQ doesn't seem able to handle complex variables for example if i want to pass the list as a variable from my shell script model="secrets toto"and --arg model "$model" => it results in "secrets toto": "secrets toto". It is being interpreted as a string, anyway around this ?
p e a k 1-Aug-20 23:04pm    
`reduce` is documented in the "Advanced Features" section of the official manual (https://stedolan.github.io/jq/manual/v1.6/). Likewise the command-line option `--argjson`.
League Of Jax 2-Aug-20 5:55am    
This saved my life thank you!!
cats n dogs 2-Aug-20 5:44am    
Hey wow i admire your patience. I am still struggling with the bonus part take a look please https://rextester.com/NKG94186
p e a k 2-Aug-20 6:31am    
That should be: reduce $model[] as

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900