FryingFinn has asked for the wisdom of the Perl Monks concerning the following question:

Hi Gang.

I just started w JSON. & I'm having a problem reading a simple? file.
I keep getting the error
"garbage after JSON object, at character offset 255 (before " "_id" : 1, "name" :...") at ./rd_students.pl line 12."

The json test file is ..

{ "_id" : 0, "name" : "Betty Boop", "subjects" : [ { "type" : "optional", "subject" : "Voice"}, { "type" : "required", "subject" : "Math" }, { "type" : "required", "subject" : "English" } ] } { "_id" : 1, "name" : "Donald Duck", "subjects" : [ { "type" : "optional", "subject" : "Accounting" }, { "type" : "required", "subject" : "Math" }, { "type" : "required", "subject" : "English" } ] }

The perl script..

#!/usr/bin/env perl use JSON; use Data::Dumper; use Perl6::Slurp; my $file = 'test.json'; my $json = slurp $file; $text = decode_json($json); print Dumper($text);

Replies are listed 'Best First'.
Re: reading JSON
by neilwatson (Priest) on Jun 16, 2015 at 18:40 UTC

    You have two documents in the json. They must be separated by commas and be in an array wrapped in [].

    [ { "_id" : 0, "name" : "Betty Boop", "subjects" : [ { "type" : "optional", "subject" : "Voice"}, { "type" : "required", "subject" : "Math" }, { "type" : "required", "subject" : "English" } ] }, { "_id" : 1, "name" : "Donald Duck", "subjects" : [ { "type" : "optional", "subject" : "Accounting" }, { "type" : "required", "subject" : "Math" }, { "type" : "required", "subject" : "English" } ] } ]

    Neil Watson
    watson-wilson.ca

Re: reading JSON
by jeffa (Bishop) on Jun 16, 2015 at 18:41 UTC

    Try enclosing the whole structure into an array ref, and don't forget commas!

    [ { "_id" : 0, "name" : "Betty Boop", "subjects" : [ { "type" : "optional", "subject" : "Voice"}, { "type" : "required", "subject" : "Math" }, { "type" : "required", "subject" : "English" } ] }, { "_id" : 1, "name" : "Donald Duck", "subjects" : [ { "type" : "optional", "subject" : "Accounting" }, { "type" : "required", "subject" : "Math" }, { "type" : "required", "subject" : "English" } ] } ]

    By the way, here is a utility i use to help debug JSON files:

    alias djson='perl -MData::Dumper -MJSON -MFile::Slurp -e"print Dumper +decode_json read_file shift"'

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    

      Nice one-liner. Thank you!
      <pocketing />