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?
In reply to How to properly check a JSONPath for existance? by Bloehdian
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |