JSON-Lines
view release on metacpan or search on metacpan
t/13-multi-object-line.t view on Meta::CPAN
use Test::More;
use JSON::Lines;
my $jsonl = JSON::Lines->new(
canonical => 1,
);
# Test: Multiple JSON objects on a single line (no newlines between them)
# This is the case when streaming output concatenates multiple JSON objects
subtest 'multiple objects on single line' => sub {
my $string = q|{"type":"init","id":1}{"type":"message","id":2}{"type":"result","id":3}|;
my @data = $jsonl->decode($string);
is(scalar @data, 3, 'decoded 3 objects from single line');
is_deeply($data[0], { type => 'init', id => 1 }, 'first object correct');
is_deeply($data[1], { type => 'message', id => 2 }, 'second object correct');
is_deeply($data[2], { type => 'result', id => 3 }, 'third object correct');
};
# Test: Mixed - some on same line, some on separate lines
subtest 'mixed single and multi-line' => sub {
my $string = qq|{"a":1}{"b":2}\n{"c":3}\n{"d":4}{"e":5}|;
my @data = $jsonl->decode($string);
is(scalar @data, 5, 'decoded 5 objects from mixed input');
is_deeply(\@data, [
{ a => 1 },
{ b => 2 },
{ c => 3 },
{ d => 4 },
{ e => 5 },
], 'all objects decoded correctly');
};
# Test: Objects with nested structures on single line
subtest 'nested objects on single line' => sub {
my $string = q|{"outer":{"inner":"value"}}{"list":[1,2,3]}|;
my @data = $jsonl->decode($string);
is(scalar @data, 2, 'decoded 2 nested objects');
is_deeply($data[0], { outer => { inner => 'value' } }, 'nested object correct');
is_deeply($data[1], { list => [1, 2, 3] }, 'list object correct');
};
# Test: Objects with escaped quotes in strings
subtest 'objects with escaped quotes' => sub {
my $string = q|{"msg":"hello \"world\""}{"msg":"test"}|;
my @data = $jsonl->decode($string);
is(scalar @data, 2, 'decoded 2 objects with escaped quotes');
is_deeply($data[0], { msg => 'hello "world"' }, 'escaped quotes preserved');
is_deeply($data[1], { msg => 'test' }, 'second object correct');
};
# Test: Objects with brackets in strings (should not confuse parser)
subtest 'brackets inside strings' => sub {
my $string = q|{"code":"if (x) { y }"}{"code":"[1,2]"}|;
my @data = $jsonl->decode($string);
is(scalar @data, 2, 'decoded 2 objects with brackets in strings');
is_deeply($data[0], { code => 'if (x) { y }' }, 'brackets in string preserved');
is_deeply($data[1], { code => '[1,2]' }, 'array-like string preserved');
};
( run in 0.344 second using v1.01-cache-2.11-cpan-140bd7fdf52 )