Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re^2: JSON Formatted String

by nvivek (Vicar)
on Jan 13, 2011 at 04:29 UTC ( [id://882027]=note: print w/replies, xml ) Need Help??


in reply to Re: JSON Formatted String
in thread JSON Formatted String

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.

Replies are listed 'Best First'.
Re^3: JSON Formatted String
by Your Mother (Archbishop) on Jan 13, 2011 at 05:54 UTC

    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!
Re^3: JSON Formatted String
by ikegami (Patriarch) on Jan 13, 2011 at 06:11 UTC

    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.

Re^3: JSON Formatted String
by Anonymous Monk on Jan 13, 2011 at 04:44 UTC
    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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://882027]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (3)
As of 2024-04-25 06:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found