Search code examples
javascriptjsonconstants

JSON on post data attach the string on it


Hey I am new to JSON and for this project I am using POST using a variable fetch_email inside the customer_porperties. Currently if I send out the value as {"$email": "sunny@gmail.com"} , it gets submitted. But if I use var fetch_email = "sunny@gmail.com" and call it on {"$email": fetch_email} , it does not submit and throws an error. What's the better way to call the variable inside the const body data for JSON ? Can anyone please help on it ?

const options = {
        method: 'POST',
        headers: {Accept: 'text/html', 'Content-Type': 'application/x-www-form-urlencoded'},
        body: new searchParams({
          data: '{"event": "game mode", "customer_properties": {"$email": fetch_email}}'
        })
      };

      fetch('https://thrid_party/api', options)
        .then(response => response.json())
        .then(response => console.log(response))
        .catch(err => console.error(err));
      

Solution

  • Don't manually build JSON strings, use the built-in JSON.stringify().

    body: new searchParams({
        data: JSON.stringify({"event": "game mode", "customer_properties": {"$email": fetch_email}})
    })