Nick Hatfield
Nick Hatfield

Reputation: 385

How can I delete parts of a JSON web response?

I have a simple Perl script and I want to remove everything up to the word "city". Or remove everything up to the nth occurrence (the 2nd in my particular case) of the comma's " , ". Here's what is looks like below.

#!/usr/bin/perl
use warnings;
use strict;

my $CMD = `curl http://ip-api.com/json/8.8.8.8`;
chomp($CMD);
my $find = "^[^city]*city";

$CMD =~ s/$find//;

print $CMD; 

The output is this:

{"as":"AS15169 Google Inc.","city":"Mountain View","country":"United States","countryCode":"US","isp":"Google","lat" :37.386,"lon":-122.0838,"org":"Google","query":"8.8.8.8","region":"CA","regionName":"California","status":"success","timezone":"America/Los_Angeles","zip":"94035"}

So i want do drop

" {"as":"AS15169 Google Inc."," 

or drop up to

{"as":"AS15169 Google Inc.","city":"Mountain View", 

EDIT:

I see I was doing far too much when matching the string. I simplified the fix for my problem with removing all before "city". My $find has been changed to

my $find = ".*city";

While I also changed the replace function like so,

$CMD =~ s/$find/city/;

Still haven't figured out how to remove all before the nth occurrence of a comma or any character / string for that matter.

Upvotes: 2

Views: 927

Answers (3)

Jan Henning Thorsen
Jan Henning Thorsen

Reputation: 126

You don't have to manually decode_json() with Mojolicious. Simply do this:

my $tx   = $ua->get('http://ip-api.com/json/8.8.8.8');
my $json = $tx->res->json;
my $as   = $json->{as}

You can even go fancy with JSON pointers:

my $as = $tx->res->json("/as");

Upvotes: 2

brian d foy
brian d foy

Reputation: 132812

The content you get back is JSON, so you can easily turn it into a Perl data structure, play with it, and even turn it back into JSON if you like. That's the point! And, it's so easy:

use Mojo::UserAgent;
use Mojo::JSON qw(decode_json encode_json);

my $ua = Mojo::UserAgent->new;

my $tx = $ua->get( 'http://ip-api.com/json/8.8.8.8' );
my $json = $tx->res->body;

my $perl = decode_json( $json );

delete $perl->{'as'};

my $new_json = encode_json( $perl );

print $new_json;

Mojolicious is wonderful for this. It's my preferred way for dealing with JSON even without the user-agent stuff. If you play with the JSON string directly, you're likely to have problems when the order of elements change or it contains wide characters.

Upvotes: 11

Nicholas Anderson
Nicholas Anderson

Reputation: 593

Something like

#!/usr/bin/perl -w

my $results = `curl http://ip-api.com/json/8.8.8.8`;
chomp $results;
$results =~ s/^.*city":"\w+\s?\w+",//g;

print $results . "\n";

should do the trick.. unless there's a misunderstanding of what you want to keep v.s. remove.

FYI, http://regexr.com/ is totally my go to for regex happiness.

Upvotes: -1

Related Questions