Search code examples
jsonperl

How can I tell if a JSON string has no elements, in Perl?


I'm trying to compare a string to another.

If it's a JSON structure which contains things, I want to print "contains things". If it's a JSON structure which doesn't contain thing, I print "empty" If it something which is not between curly brackets "{}", i print that there's an error.

Here's what I've done :

if($content =~ m/{.+}/){
    print "Contains things \n";
} elsif($content eq "{}"){
    $job_status{$url}="";
    print "empty \n";
} else {
    print "Error \n";
}

When I pass "{}" to the variable $content, he does not enter the "elsif", but go to the "else", and throw an error.

I've tried to put "==" instead the "eq" in the if, even though I know it's for numbers. When so, he enters the "elsif", and print "empty", like he should do with the "eq", and throws :

Argument "{}" isn't numeric in numeric eq (==)". 

I could use the JSON library, but I prefer not to.


Solution

  • It works for me. Does $content have a newline character? Try chomp $content;.

    use warnings;
    use strict;
    
    my $content = '{}';
    if($content =~ m/{.+}/s){
        print "Contains things \n";
    } elsif($content eq "{}"){
        print "empty \n";
    } else {
        print "Error \n";
    }
    
    __END__
    
    empty