i’m trying to parse some json in perl, but am having problems with it. i’ve read over the docs for it, but still not fully understanding how to code it. i found a few tutorials for it, but still getting errors. here is the code i have:
fetch_json_page("http://api.oodle.com/api/v2/listings?key=TEST&format=json®ion=usa&category=sale");
sub fetch_json_page
{
my ($json_url) = @_;
my $browser = WWW::Mechanize->new();
eval{
# download the json page:
print "Getting json $json_url\n";
$browser->get( $json_url );
my $content = $browser->content();
my $json = new JSON;
my $json_text = $json->allow_nonref->utf8($content);
my @decoded_json = decode_json($json_text);
print Dumper(@decoded_json), length(@decoded_json), "\n";
when i run it, i get this error
Getting json http://api.oodle.com/api/v2/listings?key=TEST®ion=usa&category=sale
[[JSON ERROR]] JSON parser crashed! malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "(end of string)") at ./oodle2.pl line 35.
which makes me wonder if i’m getting the data in properly. the url works correctly is pasted into a browser and i’ve done it fine w/ javascript, but having problems with perl. i added the print Dumper piece to try and print out the json response so i knew if the data was coming in properly
thanks
That URL returns XML, not JSON.
EDIT due to OP updating link
If you look, that’s not a valid JSON object that it’s returning thus your parser is failing. The JSON is wrapped by
jsonOodleApi(json is here);If you remove the function call thing, it’ll parse.