Krishna Mohan
Krishna Mohan

Reputation: 1523

Create JSON format from two strings in PERL

I've two string like follows in PERL script.

$labels = "firstname|lastname|email";

$values = 'krishna|mohan|[email protected]';

Now I would like to construct a JSON fromat from those two srings. I need to split (explode) both the strings base on | (pipe) symbol and construct a JSON format like follows

{"firstname":"krishna","lastname":"mohan","email":"[email protected]"}

How can I achieve this? Any Ideas would be much appreciated.

Upvotes: 0

Views: 160

Answers (1)

choroba
choroba

Reputation: 242443

Use split to "explode" the strings, build a hash from the results. Then, use JSON to translate it to JSON:

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

use JSON;

my $labels = 'firstname|lastname|email';
my $values = 'krishna|mohan|[email protected]'; # Doesn't work with double quotes!

my %hash;
@hash{ split /\|/, $labels } = split /\|/, $values;

print to_json(\%hash);

Upvotes: 3

Related Questions