1

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"}

1 Answer 1

4

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
} );
Sign up to request clarification or add additional context in comments.

10 Comments

I don't want to use any library. Can you suggest what I need to correct for it to work?
@user1595858: Yes, don't quote your string using the ' character, as I said in my answer.
@user1595858: Also, why don't you want to use a library? It's the most secure way to do what you need.
The backslashes are not the only way out - my $json = qq({"serverToken":"123"ABC",...); works just as well. See perldoc perlop for more.
@Zaid: Indeed, there are other ways, too... they all suck compared to using a proper library :)
|

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.