简体   繁体   中英

Combining all key value pairs in one using jq filter or jq play

I want to transform JSON data using jq filter

Json data:

{
 "main": [
  {
   "firstKey": "ABCD",
   "id": "12345",
   "data": [
    {
     "name": "first_id",
     "value": "first_id_value"
    },
    {
     "name": "second_id",
     "value": "second_id_value"
    },
    {
     "name": "third_id",
     "value": "third_id_value"
    }
   ]
  }
 ]
}

Expected OUTPUT :

{
 "firstKey": "ABCD",
 "id": "12345",
 "data.name.first_id": "first_id_value",
 "data.name.second_id": "second_id_value",
 "data.name.third_id": "third_id_value"
}

After many trials and errors, I was near to expected output using following filter expression

[.main[]|{"firstKey", "id"},foreach .data[] as $item (0; "data.name.\($item.name)" as $a|$item.value as $b| {($a): $b})][]

Used foreach as objects under "data" are dynamic . the number of objects can differ. The output for the above expression is:

{
  "firstKey": "ABCD",
  "id": "12345"
}
{
  "data.name.first_id": "first_id_value"
}
{
  "data.name.second_id": "second_id_value"
}
{
  "data.name.third_id": "third_id_value"
}

But I want the objects of data to be under the same braces as 'firstKey' and 'id'.

LINK to JqPlay

Any suggestions will be helpful.

Since your structure is so rigid, you can cheat and use the built-in from_entries , which takes a list of {key, value} pairs and constructs an object:

.main[] |
{firstKey, id} +
  (.data | map({key: "data.name.\(.name)", value}) |
   from_entries)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM