I have a script I have been using where a user will enter a search string and it will then return the json result of the search. I however had to make changes and let the script search for the data in a table and print a json result. I created a for loop to use perform this task. (posted a sample of the for loop which is the only relevant part here):
#!/bin/perl
use strict;
use warnings;
use JSON;
$json = JSON->new->allow_nonref;
...
foreach (...) {
my $object = {name => "$name", surname => "$surname", age => "$age"}, 'response';
my $result = $json->encode($object);
print "$result";
}
This does exactly what it use to and prints the each element in valid json format (manually made it pretty):
{
"name" : "Sarah",
"surname" : "O'Conner",
"age" : "89"
}
{
"name" : "John",
"surname" : "Smith",
"age" : "32"
}
The problem is that each each json elements are valid, but invalid as multiple root elements. I instead needed this:
[
{
"name":"Sarah",
"surname":"O'Conner",
"age":"89"
},
{
"name":"John",
"surname":"Smith",
"age":"32"
}
]
I tried 20 different ways but I just cannot fix this. Can anyone please help me with fixing this? How do I get the result as a multiple root element and separate elements?
Create an array of the "objects" (called hashes in Perl) and encode it:
my @objects;
foreach (...) {
push @objects, {name => $name, surname => $surname, age => $age};
}
my $result = $json->encode(\@objects);
print $result;
If you show us the ... part, we might show you how to translate it to @objects directly without pushing (e.g. using a map).
BTW, there's no need to doublequote variables.
You're doing the JSON conversion at the wrong point of the process. Instead of converting each individual record, you should create an array of your records and convert that.
#!/bin/perl
use strict;
use warnings;
use JSON;
$json = JSON->new->allow_nonref;
...
my @objects;
foreach (...) {
my $object = {name => "$name", surname => "$surname", age => "$age"};
push @objects, $object;
}
my $result = $json->encode(\@objects);
print "$result";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With