PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 24, 2022

[FIXED] How to group the JSON object by a key using JSONata

 July 24, 2022     json, jsonata     No comments   

Issue

I want to use JSONata to do the grouping of json objects in an array based on a key within the JSON object.

For example, I want to group the cars based on their names for the JSON example given below.

[
  {
    "car" : "audi",
    "color" : "blue",
    "reg" : 133434
  },
   {
    "car" : "benz",
    "color" : "red",
    "reg" : 134444
  },
   {
    "car" : "audi",
    "color" : "red",
    "reg" : 134884
  }
]

Expected output

{
  "audi" : [
    {
    "car" : "audi",
    "color" : "blue",
    "reg" : 133434
    },
    {
    "car" : "audi",
    "color" : "red",
    "reg" : 134884
    }
  ],
  "benz" : [
    {
    "car" : "benz",
    "color" : "red",
    "reg" : 134444
    }
   ]
}

Solution

$${car: [$.{"car": car, "color": color, "reg": reg}]}

The documentation almost gives the solution:

https://docs.jsonata.org/sorting-grouping

To make sure that the values (even if there is only a single one) for each group is stored in an array, an explicit list construction with [...] is needed.



Answered By - CC.
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing