LearningCpp LearningCpp - 1 year ago 194
Perl Question

How to parse a json file without using json library and json parser

Below are the input and Output Details

Input : This is just a sample input and real input is huge and is just in a single line

[{"mnemonic":"PT.IA1","ID":"000628"}, {"mnemonic":"EOR.1","ID":"000703"}]

code : I'm trying to read the file by setting the delimiter as }, so that I get each value,but as its a single line file, its printing everything at one, how do I parse this line by setting a delimiter to this line , is split function
enough to do this job ?

our $conf =
chunk_separator => '\{,',
open( FH, "Etot_Data.txt" ) or die $!;
while ( my $chunk = <FH> ){
my $sections = [ split $conf->{chunk_separator}, $chunk ]
print "$chunk\n";


I would want to pick "ID" from each value and prepend "abc." to it
Final String would look like abc.000628 or abc.000703 and save it in a hash
There's no need of another values except the ID in json string
Is it possible to read the json file as a normal file and operate on it.
I don't have json parser and I don't have an option to use it

Thanks for the help

Answer Source

If you can't install any external modules, you can sure include it...

Create a JSON directory in the same directory your script is in, then copy the contents of the JSON::PP module, and put it into a PP.pm file inside of the JSON directory you just created. Then, in your script, add the current working directory as a library directory: use lib '.';, and use JSON::PP;.

use warnings;
use strict;

use lib '.';

use JSON::PP qw(decode_json);

my $j;

    local $/;
    open my $fh, '<', 'file.txt' or die $!;
    $j = <$fh>;

my $p = decode_json $j;

for (@$p){
    my $id = 'abc.' . $_->{ID};
    print "$id\n";



If you need to hide the fact you've created an additional module, with only slight finagling, you can make some changes to the module, and include it directly within the script itself.

Note that JSON::PP is in Perl core in v5.14+. OP stated in comments that they are on 5.10.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download