Simon. Simon. - 4 months ago 11
JSON Question

How to remove an object from an array in Perl

I have a JSON string strcutred like so:

[{"ip":"", "comment":""}, {"ip":"", "comment":""}]

I'm trying to figure out how to remove one of these objects by identification from the IP and/or comment keys.

The closest i've got so far is this:

my $jsn = decode_json('[{"ip":"", "comment":"one"}, {"ip":"","comment":"two"}]');

if($_->{ip} eq ''){
print "Found!";
splice @{$jsn}, $_, 1;

I know splice doesn't work in this example. If i could get the index of the object (ideally without a counter), i think i could then remove the correct object.


grep is your friend here. It creates a new list of elements in an existing list that match an expression.

my @filtered = grep { $_->{ip} ne '' } @$jsn;