简体   繁体   中英

Unable to pass nodejs variable into JSON string

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

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 .

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)

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
  })
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM