How can I validate the response data in fetch api vanilla javascript?

Viewed 21

Can anyond explains me that how can I validate the response coming from fetch api call?

{"menu": {
  "id": 123,
  "value": "String or null or empty string",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  },
},
"gender":"male",
"date":"2014-08-03 18:11:34"
}

If validate that response.menu.id is not empty then run. But what about undefined?

Can I validate everything like php and typescript does and set it default as null if keys are not set. To prevent invalid object key value or parse, undefined error.

Also I want functions that validate each api before I use without using any dependencies.

const userAction = async () => {
  const response = await fetch('http://example.com/movies.json');
  const myJson = await response.json(); //extract JSON from the http response
  // I will put that functions and send response as well and that will return final filtered output. Like validate and sanitize callback.
}
0 Answers
Related