Taking data from one Json and saving in another [Perl]

Asked

Viewed 64 times

1

Good evening, I would like to know if there is a way to take data from one json and save it to another automatically without having to treat json as "text" (regex) in this case, I have already used the perl JSON module ( use JSON; ) but it was for a simpler utility, I’ve done some searching and I haven’t found anything like this that I need.

json that I will "take out" the information is that way :

[{"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 more or less like this :

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

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

I thank you in advance for your help.

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 });

By the way 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
  ]
]
  • It worked perfectly, actually solved two things I needed to do with the Perl option.

  • @edufgimenez, great! Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.