1

Need to validate the data form JSON file. Example JSON: Expected

{
   id => "12345",
   flag=> true
}

I need to throw error if the file having data like below

{
   id => 12345,
   flag=> "true"
}

I found this link for validating the string here

But if there any other solution, it would be helpful for me. TIA

Senthil
  • 55
  • 8

1 Answers1

2

Is $val a String?

The linked answer won't help you differentiate "12345" from 12345. To check if a value is stored as a string, you can use

use B qw( svref_2object SVf_POK );

svref_2object(\$val)->FLAGS & SVf_POK
   or die("Not a string\n");

This should work for the values from your JSON parser, but it won't work if you can expect dual vars, objects with overloads or magical scalars.


Is $val a Boolean?

The most popular JSON parsers use special objects to represent true and false in JSON.

With Cpanel::JSON::XS, you can use

Cpanel::JSON::XS::is_bool($val)
   or die("Not a boolean\n");

JSON::XS and JSON::PP also provide some means of checking.

ikegami
  • 367,544
  • 15
  • 269
  • 518