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

Hello monks,

aim of the following code is to find out the data type of the root element of a JSON structure which is, in the structure, clearly an array of objects.

#!/usr/bin/perl use JSON::Path; $json = q( [ { "obj1": "one" }, { "obj2": "two" } ] ); $perl = [ { "obj1" => "one" }, { "obj2" => "two" } ]; $json_path = JSON::Path->new( q($[0:]) ); print "ref: " . ref( $json_path->values( $json ) ) . "\n"; @arr = $json_path->values( $json ); print "num (w/o array):" . scalar( $json_path->values( $json ) ) . "\n +"; print "num (w array):" . scalar( @arr ) . "\n"; print "ref: " . ref( $perl ) . "\n";

Output:

ref: HASH num (w/o array):HASH(0x1baf0f0) num (w array):2 ref: ARRAY

But, when trying to use JSON::Path->values() and ref() to explicitly disclose the data type of this element, the function returns "HASH" as the type of reference, which is in contrast to what was assumed above.

Interestingly, as a second task, finding out the number of array members by assigning the return value of JSON::Path->values() to an auxiliary array @arr and evaluating this array in scalar context reveals the correct number of array elements (2). This isn't the case when the method is executed in scalar context directly.

The use of the variable $perl in the code was only applied to mimic what is expected if the root element in the JSON structure would be accessed using $json_path as assumed like above explained. For this, an "ordinary" nested perl data structure was used as the data source instead of the JSON structure.

Why does JSON::Path behave like that and how could I access the (root) array, so that application of ref() would return "ARRAY" as expected?

Will be grateful for Your help.

  • Comment on Explanation of JSON::Path behaviour when trying to find out data type of root element being an array
  • Select or Download Code

Replies are listed 'Best First'.
Re: Explanation of JSON::Path behaviour when trying to find out data type of root element being an array
by trippledubs (Deacon) on Apr 17, 2018 at 03:07 UTC
    I am feeling your pain right now after trying to figure it out also --> Bug