in reply to Need something like a SQL query for JSON data structures (JSON::XS)

If you read your data with JSON, you can use grep in the intended way, see below. However, the SQL you provided would not return any records for the example data as none of the fields equals 'taco'. So I have been using matching instead of test for equality below and I am testing only two fields. HTH.

use strict; use warnings; use Data::Dumper; use JSON; my $json = <<'JSON'; { "People" : [ { "name" : "bob", "title" : "janitor", "email" : "taco@blah.com", "iq" : "180", "favorite_food" : "wagyu steak" }, { "name" : "joe", "title" : "software engineer", "email" : "", "iq" : "80", "favorite_food" : "raw hamburger" }, { "name" : "sandy", "title" : "dishwasher", "email" : "", "iq" : "240", "favorite_food" : "tacos" }, { "name" : "george", "title" : "software engineer", "email" : "", "iq" : "14", "favorite_food" : "tacos" } ] } JSON my $j = JSON->new->decode($json); my @results2 = grep { $_->{email} =~ /taco/ or $_->{favorite_food} =~ +/taco/ } @{ $j->{People} }; print Dumper \@results2;
  • Comment on Re: Need something like a SQL query for JSON data structures (JSON::XS)
  • Download Code

Replies are listed 'Best First'.
Re^2: Need something like a SQL query for JSON data structures (JSON::XS)
by walkingthecow (Friar) on Sep 06, 2013 at 06:07 UTC
    Thank you! Thank you! Thank you!!! That perfectly solved my issue; though I'm not entirely sure how to grep the value of all keys without knowing what they keys are named, but that much I can figure out. I really appreciate the fast help! Thanks again ;)

    Update

    Figured it out:

    #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; use JSON::XS; use File::Slurp qw(read_file); my $lines = decode_json( read_file("test.json") ); my @results = grep { grep { $_ =~ /taco/ } values %$_ } @{ $lines }; print Dumper \@results;
    Thanks again hdb!

      With a simple hash, to grep the keys:

      my @results = grep /taco/, keys %hash;

      To grep the values:

      my @results = grep /taco/, values %hash;

      To get the keys whose values match a regex:

      my @results = map {$hash{$_} =~ /taco/ ? $_:  ()} keys %hash;
        json_decode in my context returns an array of hash references. I posted the method that worked for me, though there may be an easier/better way to do it.