1

Using Perl to encode hash to be use by Java program. The JSON encode converts a single key to JSON array element.

my %attribute;
push (@{$attribute {"Color"}},'Green');
push (@{$attribute {"Model"}}, ('Model_1','Model_2'));
print Dumper(\%attribute);
my $json_attr = JSON->new->utf8->encode(\%attribute);
print $json_attr;

Output:

$VAR1 = {
    'Model' => [
        'Model_1',
        'Model_2'
        ],
    'Color' => [
        'Green'
        ]
};
{"Model":["Model_1","Model_2"],"Color":["Green"]}

I need that the single key in the hash will look like this: {"Color":"Green"} (without the square brackets) Thanks.

1 Answer 1

6

First you create an array, and want it looks like not array? May be not create it? No array = no problems.

$attribute{'Color'} = 'Green';

But if you really need to do this you can use map:

%attribute = map {
   $_, @{$attribute{$_}} == 1 ? $attribute{$_}[0] : $attribute{$_}
} keys %attribute;
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.