How to encode this string to JSON?

11,651

Solution 1

Ratna is right - you can not encode a simple string (unless you put it in a list or hash)

Here are a couple of variants to encode your string:

use strict;
use warnings;
use JSON;

my $user = "Johnny";

my $json_string = { error_message => qq{{"error" : "User $user doesn't exist."}} } ;
$json_string    = to_json($json_string);
print "$json_string\n";

#i think below is what you are looking for
$json_string = { error => qq{"User $user doesn't exist."} };
$json_string    = to_json($json_string);
print $json_string;

Solution 2

JSON should be either {key:value} or [element]

The given error string:

qq{{"error" : "User $user doesn't exist."}}

is invalid as far as I know.

Solution 3

I don't know if the functionality was added after the responses, but you CAN encode a json string using perl, using the JSON module.

Using allow_nonref:

$json = $json->allow_nonref([$enable])

$enabled = $json->get_allow_nonref

If $enable is true (or missing), then the encode method can convert a non-reference into its corresponding string, number or null JSON value, which is an extension to RFC4627. Likewise, decode will accept those JSON values instead of croaking.

Code and quote from https://metacpan.org/pod/release/MAKAMAKA/JSON-2.90/lib/JSON.pm#allow_nonref

Share:
11,651
Sandra Schlichting
Author by

Sandra Schlichting

Updated on June 04, 2022

Comments

  • Sandra Schlichting
    Sandra Schlichting almost 2 years

    I have this JSON string

    $json_string = qq{{"error" : "User $user doesn't exist."}};
    

    which I construct in a low level way, so to speak.

    How do I encode it using the JSON module?

    Right now I encode hashes like this

    use JSON;
    my $json_string;
    
    my $json = JSON->new;
    $json = $json->utf8;
    
    my $data;
    $data->{users}  = $json->encode(\%user_result);
    $data->{owners} = $json->encode(\%owner_result);
    $json_string    = to_json($data);
    
    print $cgi->header(-type => "application/json", -charset => "utf-8");
    print $json_string;