Bloehdian has asked for the wisdom of the Perl Monks concerning the following question:
I want to check whether a JSONPath in a corresponding file exists, independent of the type of value associated with it (i.e., a scalar, array, object). The following code is near to what I am l looking for.
I test whether the path's value is defined, which works fine except for the case that the value associated with the path is "null": The path obviously exists, but the program indicates that it is not existant:
#!/usr/bin/perl use JSON::Path; $json = q({ "key": "value", "object": { "elem1": "value1", "elem2": "v +alue2" }, "array": [ 0, 1], "not_defined": null }); $json_path[0] = JSON::Path->new( "\$.key" ); $json_path[1] = JSON::Path->new( "\$.object" ); $json_path[2] = JSON::Path->new( "\$.non_exist" ); $json_path[3] = JSON::Path->new( "\$.array" ); $json_path[4] = JSON::Path->new( "\$.not_defined" ); for ( $i=0; $i<=$#json_path; $i++) { print "Path $json_path[$i] "; if ( defined $json_path[$i]->values( $json ) ) { print( "exists\n" ) ; } else { print( "does not exist\n" ) } }
The output is:
Path $.key exists Path $.object exists Path $.non_exist does not exist Path $.array exists Path $.not_defined does not exist
How can I do this properly?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: How to properly check a JSONPath for existance?
by kroach (Pilgrim) on Apr 02, 2018 at 16:24 UTC | |
by Bloehdian (Beadle) on Apr 02, 2018 at 17:26 UTC | |
|
Re: How to properly check a JSONPath for existance?
by Your Mother (Archbishop) on Apr 03, 2018 at 04:04 UTC |