http://www.perlmonks.org?node_id=881909


in reply to JSON Formatted String

Use JSON::XS (which JSON will load if it's installed). Your JSON will be correct. I guarantee it, or your money back.

Replies are listed 'Best First'.
Re^2: JSON Formatted String
by nvivek (Vicar) on Jan 13, 2011 at 04:29 UTC

    I know that I can catch the error in particular function can be caught by using $@ variable. I will receive JSON formatted string from client socket. Then, I will pass that to from_json method to convert it into Perl Hash structure. Before I pass the string to that function, I want to verify whether the received string is in correct JSON format. If somebody knows function in JSON to check correct JSON string or not. Kindly help me out of this problem.

      I think you sort of answered your question there already. You just do it and catch the errors. No errors: valid, proceed. Errors... you decide what happens next. E.g.-

      use warnings; use strict; use JSON::XS; use Try::Tiny; my %json = ( empty_obj => "{}", empty_array => "[]", bare_string => "hai", obj => qq|{"o":"hai"}|, bad_obj => qq|{o:hai}|, ); for my $name ( keys %json ) { printf "%11s --> ", $name; try { my $throw_away = decode_json($json{$name}); print "OK!\n"; } catch { print "Error: $_"; }; } __END__ obj --> OK! bare_string --> Error: malformed JSON string, neither array, object, n +umber, string or atom, at character offset 0 (before "hai") at ... empty_obj --> OK! bad_obj --> Error: '"' expected, at character offset 1 (before "o: +hai}") at ... empty_array --> OK!

      Before I pass the string to that function, I want to verify whether the received string is in correct JSON format

      I know that I can catch the error in particular function can be caught by using $@ variable

      I'm confused. You've just answered your own question.

      my $valid = eval { $json->decode($input); 1 };

        Thanks a lot. It is working for me.

      Either you trust the JSON module to do its job, or you don't -- why wouldn't you trust the JSON module?

        I am trusting the JSON module but I need to verify it because in a network data may get changed.