-1

I am working on a web application in which I make an API call which returns a response.text() in the form below:

{
  "results": [
    {
      "uuid": "1c661e96-750a-5039-9a7e-676a5b46ad42",
      "display": "1004NG - Sarah Gen Mathews",
      "links": [{ "rel": "self", "uri": "http://localhost:8080/my-url" }]
    }
  ]
}

I am new to working with APIs so after receiving this, I am not sure how to access the individual parts of this text from my code. For example, I would like to store the uuid in a variable. This is my fetch() code section:

fetch(url, requestOptions)
  .then((response) => response.text())
  .then((result) => console.log(result))
  .catch((error) => console.log("error", error));

Any help would be greatly appreciated!

Tal
  • 43
  • 1
  • 7
RayanGad
  • 1
  • 3
  • The response is JSON. So use `.json()` instead of `.text()` + [Working with objects - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects) – Andreas Jul 29 '22 at 11:48

1 Answers1

1

You should use the json() function 99% of the time when you're getting json data.

You can do this by having:

fetch(url, requestOptions)
  .then((response) => response.json())
  .then((data) => {
    let uuid = data.results[0].uuid // get uuid from json
    console.log(uuid)
});

Although if you can, you should use the async await API

let uuid = ''

const resp = await fetch(url, requestOptions)
const json = await resp.json()

uuid = json.results[0].uuid // get uuid from json
console.log(uuid)

Check out the MDN docs for more info.

Tal
  • 43
  • 1
  • 7
  • _"...99% of the time."_ - `.json()` only makes sense when the response is actually JSON. Why would you call `.json()` when the response is plain text or markup or a blob or ... ? – Andreas Jul 29 '22 at 12:19
  • _"You can do this by having: `let uuid = "" ...`"_ - That's a terrible idea/example -> [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Andreas Jul 29 '22 at 12:20
  • Most of the time you're getting json data, but I will change it. – Tal Jul 29 '22 at 12:21
  • _"Most of the time you're getting json data..."_ - No. You get whatever the API you're calling returns... – Andreas Jul 29 '22 at 12:21
  • This doesn't work. The response is text so doesn't make sense to use response.json(). – RayanGad Jul 29 '22 at 21:46
  • I've been able to answer this by adding to @Tal answer and first parsing the text response to Json then dealing with the contents as such. `fetch(url, requestOptions) .then((response) => response.text()) .then((data) => { let jsonObj = JSON.parse(data) let uuid = jsonObj.results[0].uuid console.log(uuid) });` – RayanGad Jul 29 '22 at 21:50