1

I've got very little experience with JSON and jq and am struggling to reformat my JSON objects. Each object contains a couple of key/value pairs and an array of objects. I'm trying to resturcture each object so that it's just a list of key/value pairs (i.e. extract the objects in the array).

[
   {
      "key1":"value1",
      "key2":"value2",
      "key 3":[
         {
            "a":"key_to_be_extracted_1",
            "v":"value_to_be_extracted_1"
         },
         {
            "a":"key_to_be_extracted_2",
            "v":"value_to_be_extracted_2"
         }
      ]
   },
   {
      "key1":"value1",
      "key2":"value2",
      "key 3":[
         {
            "a":"key_to_be_extracted_1",
            "v":"value_to_be_extracted_1"
         },
         {
            "a":"key_to_be_extracted_2",
            "v":"value_to_be_extracted_2"
         }
      ]
   }
]

What I'm trying to get to is:

[
   {
      "key1":"value1",
      "key2":"value2",
      "key_to_be_extracted_1":"value_to_be_extracted_1",
      "key_to_be_extracted_2":"value_to_be_extracted_2"
   },
   {
      "key1":"value1",
      "key2":"value2",
      "key_to_be_extracted_1":"value_to_be_extracted_1",
      "key_to_be_extracted_2":"value_to_be_extracted_2"
   }
]

Any help with this would be amazing!!

2 Answers 2

1

jq has a from_entries function that expects an array of {key, value} objects and produces an object. Thus, you can transform your "key 3" value into such an array and produce an object like so:

."key 3" | map({key: .a, value: .v} | from_entries

Putting that together with a map that just copies the two other keys:

map({key1, key2} + (."key 3" | map({key: .a, value: .v}) | from_entries))

Sign up to request clarification or add additional context in comments.

Comments

0

If you want to avoid having to specify the keys to retain, you could go with:

map( .
     + (."key 3" | map( {(.a): .v} ) | add )
     | del(."key 3") )

That is, add in the new key-value pairs, and then delete "key 3". Notice also that add has been used here instead of from_entries, making for a more succinct and perhaps more straightforward solution.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.