4

how do I parse a JSON string in Perl?

Note: I am a C++/Java/C# software engineer, not a Perl-wielding scripter.

I have fully read the JSON.pm "documentation" to find a working example, but those docs turned out to be complete and utter garbage".

I also read this post, but no one seems to know how to get the JSON key, value pairs out of the decoded perl variable.

Here is my script. Can someone help?

use JSON;

my $json_string = '{"foo": "bar"}';
my $decoded_json = decode_json($json_text);
print $decoded_json["foo"];

std::map<string, string> mymap = convert_to_cplusplus(decoded_json); # doesn't work
my asfjsa;fjsa;fwe # doesn't work

I got frustrated near the end.

7
  • 2
    To the downvoter: There's no need to downvote this question...the OP was just a little frustrated, and in this instance, I can actually understand. The documentation was written with a seasoned Perl programmer in mind, so it's rather daunting if you're not such. Commented Sep 2, 2011 at 6:47
  • 4
    @Chris: Maybe this has to do with the general tone. C++ is magic to me but that wouldn't warrant me call the documentation of a C++ lib garbage when it is written for a seasoned C++ programmer. (I didn't downvote though.) Commented Sep 2, 2011 at 7:10
  • 5
    humph. What's with the implication that Perl programmers can't be software engineers? I didn't downvote either, but I'm not very tempted to help either. Commented Sep 2, 2011 at 8:00
  • 3
    I do not think you have to be a seasoned Perl programmer to understand the docs. As in other documentation it is assumed that you understand the Perl datastructures. That is one of the minimum requirements no matter what language you write in. Commented Sep 2, 2011 at 8:44
  • 5
    -1 for the tone. Change the question into an emotionally neutral wording and substantiate your opinion why something is garbage. Commented Sep 2, 2011 at 9:35

1 Answer 1

13

You need to use $decoded_json->{"foo"}---note the curly brackets, not the square ones. Also note the arrow ->---decode_json returns a reference.

I will readily admit that the documentation in this case is no help for someone who doesn't already know Perl, for example, to the level of knowing what $perl_hash_or_arrayref means. (A seasoned Perl programmer knows instantly it means you have to use ->.)

Sign up to request clarification or add additional context in comments.

3 Comments

You beat me to it. I also wanted to post a link to the perlref page: perldoc.perl.org/perlref.html
@Igor: +1 Neat idea, though I think perlreftut might be a better idea. I think perlref will go over the poor OP's head. :-(
@Chris - it doesn't take a seasoned programmer to understand how to dereference a hash. Just a mildly competent one

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.