Search code examples
javascriptjsonstringify

How to get variable and pass value to API using JSON.stringify


I need to pass these values ​​to an API using JSON.stringify and I need to get the variables in the object. The object that the API receives needs to look exactly like this:

{
  "sessionInformation": "{\"emailAddress\" : \"the value\",\"firstName\" : \"the name\", \"question\" : \"the text\"}"
}

I'm trying this, but I'm not sure exactly how to concatenate the variables in that context

const email = some.value,
const name = some.value,
const text = some.value,

const raw = JSON.stringify({
  sessionInformation:
     '{"emailAddress" : email,"firstName" : name, "question" : text}',
});

How can I solve this? Thanks


Solution

  • You need to stringify internal object as well

    const email = "Email value";
    const name = "Name value";
    const text = "Text value";
    
    const raw = JSON.stringify({
      sessionInformation: JSON.stringify({
        emailAddress: email,
        firstName: name,
        question: text
      }),
    });
    
    console.log(raw)