1

I have a long output contains a list of items, I'm wondering how I can print it in JASON format.

DLQ_CPP_LTEST
PCA
LTEST_H
ActiveMQ.DLQ
LTEST
DLQ_CPP_NMP_STUDY

Desired output

{
 "data":[
  { "{#AMQQ}":"DLQ_CPP_LTEST" },
  { "{#AMQQ}":"PCA" },
  { "{#AMQQ}":"LTEST_H" },
  { "{#AMQQ}":"ActiveMQ.DLQ" }
]

}

I have tried modifying a perl script I have, but I couldn't get the output to show correctly.

#!/usr/bin/perl
use strict;
use warnings;

# Options
my $_proc = "/root/query.txt";

# Validate options
 if ( ! -e $_proc)
{
    die "File $_proc not found!";
}

# Keep count
my $_first = 1;

# Present the data in JSON format
print "{\n";
print "\t\"data\":[\n\n";

# Fetch the data and put it in an array
my @_data = `cat $_proc | awk '{ print \$1 }'`;
chomp @_data;

# Read the array and print the wanted data
 foreach my $_disk (@_data)
{
    # Print the data in JSON
    print "\t,\n" if not $_first;
    $_first = 0;

    print "\t{\n";
    print "\t\t\"{#AMQQ}\":\"$_disk\"\n";
    print "\n\t}\n";
}

print "\n\t]\n";
print "}\n";

Thanks for your help

1 Answer 1

5

Build your data structure, and then just use the JSON module:

use strict;
use warnings;

use JSON;

my %hash = (data => [map {chomp; {"{AMQQ}" => $_}} <DATA>]);

print to_json(\%hash);

__DATA__
DLQ_CPP_LTEST
PCA
LTEST_H
ActiveMQ.DLQ
LTEST
DLQ_CPP_NMP_STUDY

Outputs:

{"data":[{"{AMQQ}":"DLQ_CPP_LTEST"},{"{AMQQ}":"PCA"},{"{AMQQ}":"LTEST_H"},{"{AMQQ}":"ActiveMQ.DLQ"},{"{AMQQ}":"LTEST"},{"{AMQQ}":"DLQ_CPP_NMP_STUDY"}]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.