Hi. I'm looking for a simple way to parse JSON objects out of a stream.

I am calling an HTTP service that returns a stream of json objects over time.

To read it, i registered a simple callback handler in LWP::UserAgent

$ua->add_handler( response_data => sub { my($response, $ua, $h, $data) = @_; return "true" if $data =~ /^\s*$/; print "Callback triggered\n"; print "data: .${data}.\n"; my $result = eval { $json->decode( $data ) }; if ($@){ print "error: $@\n"; return "true"; }; print Dumper $result; return "true"; } );

As expected, i sometimes get partial json objects in $data.

My first idea would be to so something like m/{.*?}/ against $data. Or rather some more elaborate version that deals with balanced parens and quoted strings.

My question is, is there an easier / simpler / more straightforward way to deal with something like this that I am missing?

-- Sec
EDIT: to clarify a bit.

The problem is that in the callback $data may just be

{ "foo": "bar" } { "foo" : "q
which means I have to grab one object, handle it, keep the rest and wait for more data.

I know how to write code for that "the long way". I was asking if there is something clever or an existing module that can help with this.


In reply to Parsing JSON out of an incremental stream by Sec

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.