
Let's say you are using the 'parse_json' module.
use JSON::Parse 'parse_json';
In this example, the JSON is stored in a variable named raw_json.
my $raw_json = '{"key1":"foo", "key2":true, "key3":false, "key4":null}';
The JSON is parsed into the $parsed_json variable.
my $parsed_json = parse_json($raw_json);
Dumper can be used to print the parsed json.
use Data::Dumper;
print Dumper $parsed_json;
Dumper should produce something like this.
$VAR1 = {
'key1' => 'foo',
'key2' => 1,
'key3' => '',
'key4' => undef
};
Attempting to modify the value of key2, key3, or key4, like this . . .
$parsed_json->{key2} = "bar";
. . . will produce the following, because "true", "false", and "null" are literals, and the 'parse_json' module maps literals to read-only values.
Modification of a read-only value attempted
One option is to delete the key value pair.
delete $parsed_json->{key2};
And to then create the key with a value.
$parsed_json->{key2} = "bar";
parse_json_safe
Or, the parse_json_safe module can be used. With the 'parse_json_safe' module, "true", "false", and "null" are NOT mapped to read-only values.
use JSON::Parse 'parse_json_safe';
In this example, key2 is updated to contain a value of bar.
$parsed_json->{key2} = "bar";
Dumper should produce something like this.
$VAR1 = {
'key1' => 'foo',
'key2' => 'bar',
'key3' => '',
'key4' => undef
};
New JSON object
Or, if you do not want to use parse_json_safe, you can create a new JSON object.
my $new_json_object = JSON::Parse->new ();
Then use the copy_literals module so that "true", "false", and "null" are NOT mapped to read-only values.
$new_json_object->copy_literals(1);
Then use the run module and store the output into the $parsed_json variable.
my $parsed_json = $new_json_object->run ($raw_json);
In this example, key2 is updated to contain a value of bar.
$parsed_json->{key2} = "bar";
Dumper should produce something like this.
$VAR1 = {
'key1' => 'foo',
'key2' => 'bar',
'key3' => '',
'key4' => undef
};
Did you find this article helpful?
If so, consider buying me a coffee over at