Home > database >  Unable to pass nodejs variable into JSON string
Unable to pass nodejs variable into JSON string

Time:11-02

How can I pass sns_NameSpace variable into the payload? I'm getting the error Unrecognized token sns_NameSpace. I tried to stringfy using JSON and yet still I get the same error.

Error:

   "errorMessage": "Could not parse request body into json: Could not parse payload into json: Unrecognized token 'sns_NameSpace': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')\n at [Source: (byte[])\"{ \"Host\": sns_NameSpace, \"Key\": sns_key, \"Value\": \"1\"}\"; line: 1, column: 25]",

code:

   var sns_NameSpace = sns.Trigger.Namespace;
   var sns_NameSpace = JSON.stringify(sns_NameSpace.replace("/", "_"));
   var sns_key = JSON.stringify(sns_ApiId   '_'   sns_MetricName);

  var params = {
    FunctionName: 'zabbixPy', // the lambda function we are going to invoke
    InvocationType: 'RequestResponse',
    LogType: 'Tail',
    Payload: '{ "Host": sns_NameSpace, "Key": sns_key, "Value": "1"}'
  };

CodePudding user response:

Assuming you have a valid string you should be able to use template literals for this.

EX:

var params = {
    ...
    Payload: `{ "Host": ${sns_NameSpace}, "Key": ${sns_key}, "Value": "1"}`
};

Also, I'd recommend using different variable names instead of defining, then re-defining sns_nameSpace.

CodePudding user response:

This question should be renamed "How do I concatenate a variable and a string?". The issue is on your "Payload" line.

Problem: variable being interpreted literally

Here is the string that is not working:

'{ "Host": sns_NameSpace, "Key": sns_key, "Value": "1"}'

As you can see from the error message, sns_NameSpace is not being replaced and so is being interpreted literally, as an invalid JSON token.

Solution 1: string concatenation

One can concatenate strings using the string concatenation operator ( )

'{ "Host": '   sns_NameSpace   ', "Key": '   sns_key   ', "Value": "1"}'

Solution 2: template strings

Or can use template strings to as so:

`{ "Host": ${sns_NameSpace}, "Key": ${sns_key}, "Value": "1"}`

Please note that the template string uses ` (backtick), not ' (single quote)

CodePudding user response:

It would be a lot more straight-forward to build the object in JS and then stringify it, instead of stringifying individual parts and having literal JSON pieces in the string:

var sns_NameSpace = sns.Trigger.Namespace;
var sns_NameSpace = JSON.stringify(sns_NameSpace.replace("/", "_"));
var sns_key = JSON.stringify(sns_ApiId   '_'   sns_MetricName);
var params = {
  FunctionName: 'zabbixPy', // the lambda function we are going to invoke
  InvocationType: 'RequestResponse',
  LogType: 'Tail',
  Payload: JSON.stringify({
    Host: sns_NameSpace.replace('/', '_'),
    Key: sns_ApiId   '_'   sns_MetricName,
    Value: 1
  })
};
  • Related