Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble With Parsing JSON with Perl

Tags:

json

parsing

perl

I have a JSON file and I'm trying to parse it in Perl. So far I have:

use strict;
use warnings;
use JSON;

open my $fh, "/Users/arjunnayini/Desktop/map_data.json";   


my @decoded_json = @{decode_json($fh)};

But I am getting an error that I have a: "malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "GLOB(0x100804ed0)") "

I'm fairly certain that the JSON file is formatted properly, so I'm not sure where this is going wrong. Any suggestions?

like image 380
Arjun Nayini Avatar asked Dec 06 '22 23:12

Arjun Nayini


1 Answers

Assuming your call to JSON is correct, you need to slurp the file in first:

#!/usr/bin/perl

use strict;
use warnings;
use JSON;

my $json;
{
  local $/; #enable slurp
  open my $fh, "<", "/Users/arjunnayini/Desktop/map_data.json";
  $json = <$fh>;
} 

my @decoded_json = @{decode_json($json)};
like image 91
Joel Berger Avatar answered Jan 05 '23 07:01

Joel Berger