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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.