4

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?

1 Answer 1

15

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)};
Sign up to request clarification or add additional context in comments.

2 Comments

or: local @ARGV = "/Users/arjunnayini/Desktop/map_data.json"; $json = <>;
Yes there are other ways to slurp in the file first. My example shows a common idiom.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.