Reputation: 83
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
Upvotes: 0
Views: 1837
Reputation: 977
Demo
https://jqplay.org/s/YbjICOd8EJ
You can also use reduce
reduce .Objects[] as $o ({}; .[$o.ElementName]=$o.ElementArray)
Upvotes: 0
Reputation: 36033
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 map
ping the input object's Objects
array.
.Objects | map({key: .ElementName, value: .ElementArray}) | from_entries
{
"Test1": [
"abc",
"bcd"
],
"Test2": [
"abc",
"bcde"
]
}
Upvotes: 1