user1595858
user1595858

Reputation: 3878

How to construct json text using string?

I'm trying to construct json text as show below. But the variables such as $token, $state, $failedServers are not been replaced with its value. Note- I don't want to use any module specifically for this to work, I just want some plain string to work. Can anyone help me ?

my $json = '{"serverToken":"$token", "state":"$state","parameters" :"$failedServers"}';

current output was:

{"serverToken":"$token", "state":"$state","parameters" :"$failedServers"}

needed output format:

{"serverToken":"1213", "state":"failed","parameters" :"oracleapps.veeralab.com,suntrust.com"}

Upvotes: 1

Views: 192

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79536

Your variables are not being replaced, because they are inside of a single-quoted string--that is, they are inside a string quoted by ' characters. This prevents variable substitution.

You will also be much better off creating JSON using a JSON library, such as this one. Simply using a quoted string is very dangerous. Suppose your one of your variables ends up containing a special character; you will end up with invalid JSON.

{"serverToken":"123"ABC", "state":"offline", "paramameters":"bugs"}

If your variables come from user input, really bad things could happen. Imagine that $token is set to equal foo", "state":"online", "foo":"bar. Your resulting JSON structure would be:

{"serverToken":"foo", "state":"online", "foo":"bar", "state":"offline" ...

Certainly not what you want.


Possible solutions:

The most blatantly obvious solution is simply not to the ' quote character. This has the drawback of requiring you to escape your double quote (") characters, though, but it's easy:

my $json = "{\"serverToken\":\"$token\", \"state\":\"$state\",\"parameters\" :\"$failedServers\"}";

Another option is to use sprintf:

my $json = sprintf('{"serverToken":"%s", "state":"%s", "parameters":"%s"}', $token, $state, $failedServers);

But by far, the best solution, because it won't break with wonky input, is to use a library:

use JSON;
my $json = encode_json( {
    serverToken => $token,
    state => $state,
    paramaters => $failedServers
} );

Upvotes: 4

Related Questions