Getting data from one Json and saving on another [Perl]

1

Good night, I would like to know if there is a way to get data from one json and save it to another automatically without needing to treat json as "text" (regex) in case, I already used perl's JSON module use JSON;) but it was for a simpler utility, I already did some searches and I did not find anything like that that I need.

json that I'm going to "get" the information is like this:

[{"name":"AK-47 | Aquamarine Revenge (Battle-Scarred)","price":1292,"have":10,"max":28},{"name":"AK-47 | Aquamarine Revenge (Factory New)","price":3769,"have":4,"max":13}]

I would like to pass only the entries that are within "name" and "price", getting something like this:

{"AK-47 | Aquamarine Revenge (Battle-Scarred)":"13.16",
"AK-47 | Aquamarine Revenge (Factory New)":"37.64"}]

I've gotten something by treating json as text, but it's not getting "good" as you're dealing with the file. Any example or idea is already welcome for me to start looking for how to solve.

Thank you in advance for your help.

    
asked by anonymous 19.09.2017 / 23:27

1 answer

2

With Perl + JSON Module:

#!/usr/bin/perl 
use JSON;
my $j = '[
  {"name":"AK-47 | Aquamarine Revenge (Battle-Scarred)",
   "price":1292,
   "have":10,
   "max":28},
  {"name":"AK-47 | Aquamarine Revenge (Factory New)",
   "price":3769,
   "have":4,
   "max":13}]';

my  $v=from_json($j);
print to_json( {map {($_->{name},$_->{price})}  @$v });

Already another alternative command jq

$ cat x.json | jq 'map([ .name , .price])'
[
  [
    "AK-47 | Aquamarine Revenge (Battle-Scarred)",
    1292
  ],
  [
    "AK-47 | Aquamarine Revenge (Factory New)",
    3769
  ]
]
    
27.09.2017 / 14:14