Search code examples
jsonlistjq

Create one big object from a list of objects using jq


Okay so I have blob of data like so ...

[
{
  "sys_replace_on_upgrade": "false",
  "initial_state": "false",
  "sys_mod_count": "0",
  "sys_updated_on": "2020-09-02 13:48:39",
  "sys_tags": "",
  "state_label": "Authorize",
  "sys_class_name": "sttrm_state",
  "state_sequence": "3",
  "sys_id": "13fc0801c343101035ae3f52c1d3ae77",
  "sys_update_name": "sttrm_state_13fc0801c343101035ae3f52c1d3ae77",
  "sys_updated_by": "admin",
  "sys_created_on": "2020-09-02 13:48:39",
  "sys_name": "Authorize",
  "state_value": "-3",
  "sys_customer_update": "false",
  "sys_created_by": "admin",
  "sys_policy": ""
},
...
]

I run it through jq like so:

jq '.result[]|{(.sys_name) : .state_value}' states.json
{
  "Authorize": "-3"
}
{
  "New": "-5"
}
{
  "Closed": "3"
}
{
  "Review": "0"
}
...

What I really want is one big object like:

{
  "Authorize": "-3" ,
  "New": "-5",
  "Closed": "3",
  "Review": "0", 
...
}

I'm close but I'm missing something ...


Solution

  • Either retain the array by modifying its items using map, then add them to summarize the object:

    .result | map({(.sys_name): .state_value}) | add
    

    Or, simpler, reduce over the items, and successively build up the object:

    .result | reduce .[] as $i ({}; .[$i.sys_name] = $i.state_value)