bsd
bsd

Reputation: 6183

How to add more JSON entries into file with right format?

I am trying to add via given input to JSON, but the output format is not as expected. Please suggest any changes require on this code. For testing I am passing one entry via $data_to_json, but I need to pass many like similar lines to JSON file.

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use JSON;
my $json = JSON->new;

my %data;
my $data_to_json = [ {data=>{user=>"myuser",status=>"ok"}, "host"=>"localhost","ver"=>"1.0", "remote"=> [{"host"=>"remotehost","ver"=>"1.0"}] } ];
$data{data} = $data_to_json;
my $convert = JSON->new->pretty;
print $convert->encode(\%data);

It returns the following output which is not expected:

{
   "data" : [
      {
         "ver" : "1.0",
         "data" : {
         "status" : "ok",
        "user" : "myuser"
     },
     "remote" : [
        {
           "ver" : "1.0",
           "host" : "remotehost"
        }
     ],
     "host" : "localhost"
   }
 ]
}

I am looking at following results format (there are more than one record like below I need to add into JSON)

[
{
    "data":{
        "user": "myuser",
        "status": "ok" 
    },
    "host": "localhost",
    "ver": "1.0",
    "remote": [
        {
            "host": "remotehost",
            "ver": "1.0",
        }
     ]
  },
{
    "data":{
        "user": "myuser",
        "status": "ok" 
    },
    "host": "localhost",
    "ver": "2.0",
    "remote": [
        {
            "host": "remotehost",
            "ver": "2.0",
        }
     ]
   }
]

Upvotes: 2

Views: 100

Answers (1)

choroba
choroba

Reputation: 242443

The outer structure is not an object in JSON parlance (or a hash in Perl parlance), but an array. Use push to add elements to an array. Also, the data can be simplified: you don't need to store the object/hash in an array, just use the object/hash directly.

my @data;
my $data_to_json = { data   => { user => 'myuser', status => 'ok' },
                     host   => 'localhost',
                     ver    => '1.0',
                     remote => [ { host => 'remotehost', ver => '1.0' } ] };
push @data, $data_to_json;
my $convert = JSON->new->pretty;
print $convert->encode(\@data);

Upvotes: 3

Related Questions