Using Raku (formerly known as Perl_6)
You need to use a JSON parser:
~$ raku -MJSON::Tiny -e 'my @json = from-json($_).list given slurp; \
my %accum.push: .<key> => .<value>.map(*.Num).Slip for @json>>.split(", "); \
.say for to-json(%accum.sort);' file
Sample Input:
[
{"key": "a", "value": 0},
{"key": "a", "value": 1},
{"key": "a", "value": 2},
{"key": "b", "value": 3},
{"key": "b", "value": 4},
{"key": "b", "value": 5}
]
Sample Output (values have been Num
-ified and Slip
ped, i.e. flattened):
[ { "a" : [ 0, 1, 2 ] }, { "b" : [ 3, 4, 5 ] } ]
The final code adds a call to to-json()
at the end. To figure out what's going on in the intermediate steps, it's probably easiest to show you the output of each individual data structure. Printing the @json
array with .say for @json;
returns the following:
{key => a, value => 0}
{key => a, value => 1}
{key => a, value => 2}
{key => b, value => 3}
{key => b, value => 4}
{key => b, value => 5}
Generating an %accum
hash with only .<key> => .<value>
(in other words, without .map(*.Num).Slip
) returns the following via a call to .say for %accum.sort;
:
[ { "a" : [ [ "0" ], [ "1" ], [ "2" ] ] }, { "b" : [ [ "3" ], [ "4" ], [ "5" ] ] } ]
Note, you can do various manipulations of the values with function calls like Num
, Int
, etc., and you can "flatten" with a call to Slip
as in the code posted at top.
Raku's JSON::Tiny
module will stringify values by default, and if you want those stringified values as a single list (instead of sub-lists), you Slip
them together.
Below, stringified values Slip
ped together:
~$ raku -MJSON::Tiny -e 'my @json = from-json($_).list given slurp; \
my %accum.push: .<key> => .<value>.Slip for @json>>.split(", "); \
.say for to-json(%accum.sort);' file
[ { "a" : [ "0", "1", "2" ] }, { "b" : [ "3", "4", "5" ] } ]
So a lot of options here for data output, the simplest being taking the code at the top and removing the final to-json()
call, to see Raku's "pairs" representation of the %accum
hash:
a => [0 1 2]
b => [3 4 5]
https://raku.land/cpan:MORITZ/JSON::Tiny
https://raku.org