0

I am trying to parse the below json file and store the result into another json file. How do I achieve this ?

{
  "Objects": [
    {
      "ElementName": "Test1",
      "ElementArray": ["abc","bcd"],
      "ElementUnit": "4"
    },
    {
      "ElementName": "Test2",
      "ElementArray": ["abc","bcde"],
      "ElementUnit": "8"
    }
  ]
}

Expected result :

{
"Test1" :[
"abc","bcd"
],
"Test2" :[
"abc","bcde"
]
}

I've tried something on the lines of the below but I seem to be off -

jq '[.Objects[].ElementName ,(.Objects[]. ElementArray[])]' user1.json

jq ".Objects[].ElementName .Objects[].ElementArray" ruser1.json

2 Answers 2

1

Your expected output needs to be wrapped in curly braces in order to be a valid JSON object. That said, use from_entries to create an object from an array of key-value pairs, which can be produced by accordingly mapping the input object's Objects array.

.Objects | map({key: .ElementName, value: .ElementArray}) | from_entries
{
  "Test1": [
    "abc",
    "bcd"
  ],
  "Test2": [
    "abc",
    "bcde"
  ]
}

Demo

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

Comments

0

Demo

https://jqplay.org/s/YbjICOd8EJ

You can also use reduce

reduce .Objects[] as $o ({}; .[$o.ElementName]=$o.ElementArray)

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.