how do I use backticks or string literals when sending a payload in Javascript without errors

I have tried the below code but doesn’t work

let sourceIPAddress = "10.255.0.8/32"
 let destinationIPAddress = "10.255.0.0/32/32"
  
 

     let filterAddValue = 
  `{'filter-name':'SessionFilter','source-ip': '${sourceIPAddress}','destination-ip':'${destinationIPAddress}'}`

  const filterAdd =
  {
    "filter-add":filterAddValue
  }
  const filterAddStringify = JSON.stringify(filterAdd);

which gives me the result shown below
"error-message": "No default namespace has been defined."

INCORRECT PAYLOAD

{"filter-add": "{‘filter-name’:’SessionFilter’,’source-ip’: ‘10.255.0.8/32′,’destination-ip’:’10.255.0.0/32′}"
}

which is has additional double quotes in front of the inner curly braces while the below which is the correct payload which doesn’t have additional double quotes in front of the inner curly braces. How can I acheive this in javascript exactly as shown in the below payload.

CORRECT PAYLOAD

{"filter-add":{"filter-name":"SessionFilter","source-ip":"10.255.0.8/32","destination-ip":"10.255.0.0/32"}} 

>Solution :

Your incorrect version is an object with a single key, and the value of that key is a long string that contains JSON data. Instead you want to have a key, and the value of that key is another object.

You can do that pretty easily by just literally typing it to look like the object you want. JSON stands for JavaScript Object Notation, so JavaScript Objects are usually valid JSON data as well.

let sourceIPAddress = "10.255.0.8/32"
let destinationIPAddress = "10.255.0.0/32/32"

const filterAdd = {
  "filter-add":{
    "filter-name":"SessionFilter",
    "source-ip": sourceIPAddress,
    "destination-ip":destinationIPAddress
  }
};

const filterAddStringify = JSON.stringify(filterAdd);

console.log(filterAddStringify)

Leave a Reply