Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding key name to value using jq

I am trying to dynamically assign the key name as its value in my json

This is the json i am using:

{
    "test1": "",
    "test2": "",
    "test3": ""
}

the result i would like to obtain looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
    "test1": "test1",
    "test2": "test2",
    "test3": "test3"
}

I am not familiar with jq and the closest result i got is using:

keys[] as $key | {"\($key)": "\($key)"} | .

here is the output:

{
  "test1": "test1"
}
{
  "test2": "test2"
}
{
  "test3": "test3"
}

>Solution :

with_entries lets you manipulate .key and .value for each field. Just set one to the value of the other:

with_entries(.value = .key)
{
  "test1": "test1",
  "test2": "test2",
  "test3": "test3"
}

Demo


Following your approach, you might want to consider reduce for an iterative manipulation, and keys_unsorted which acts like keys but produces the keys in the original (unsorted) order:

reduce keys_unsorted[] as $key (.; .[$key] = $key)

Demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading