Home > Software design >  How to nest JSON inside "data:"{} object for POST fetch request?
How to nest JSON inside "data:"{} object for POST fetch request?

Time:06-21

Long time listener, first time caller.

I've created a form and sending a fetch request to my database (Xano). My JSON object looks like the below snippet.

{
  "job_type": "full-time",
  "job_title": "3D Art Director",
  "job_location": "remote",
  "job_level": "senior",
  "salary": "$600 day"
}

But Xano needs it to be one level deeper inside "data", otherwise I can't map things up with dot notation...

{
  "data": {
    "job_type": "full-time",
    "job_title": "3D Art Director",
    "job_location": "remote",
    "job_level": "senior",
    "salary": "$600 day"
  }
}

My JS is below. So where and how can I make the JSON response sit inside "data:"{} ? (I am a complete JS Noob and my code is a Frankenstein monster from various sources as I learn!)

document.addEventListener('DOMContentLoaded', () => {
    document.getElementById('jobForm').addEventListener('submit', handleForm);
  });

  function handleForm(ev) {
    ev.preventDefault(); 
    let jobForm = ev.target;
    let fd = new FormData(jobForm);

    //look at all the contents
    for (let key of fd.keys()) {
      console.log(key, fd.get(key));
    }
    let json = convertFD2JSON(fd);

    //send the request with the formdata
    let url = 'https://hookb.in/eKjeKejY6NhlaRPldLNP';
    let h = new Headers();
    h.append('Content-Type', 'application/json');

    let req = new Request(url, {
      mode: 'cors', // no-cors, *cors, same-origin
      headers: h,
      body: json,
      method: 'POST',
    });

    fetch(req)
      .then((res) => res.json())
      .then((data) => {
        console.log('Response from server');
        console.log(data);
      })
      .catch(console.warn);
  }

  function convertFD2JSON(formData) {
    let obj = {};
    for (let key of formData.keys()) {
      obj[key] = formData.get(key);
    }
    return JSON.stringify(obj);
  }

CodePudding user response:

You can do something like :

  function convertFD2JSON(formData) {
    let obj = {
       data: {}
    };
    for (let key of formData.keys()) {
      obj.data[key] = formData.get(key);
    }
    return JSON.stringify(obj);
  }

CodePudding user response:

Simply build your required object structure before serializing it:

function convertFD2JSON(formData) {
  const data = {};
  for (let key of formData.keys()) {
    data[key] = formData.get(key);
  }
  return JSON.stringify({ data }); // same as { data: data }
}
  • Related