Help

The Community will be undergoing maintenance from Friday February 21 - Friday, February 28 and will be "read only" during this time. To learn more, check out our Announcements blog post.

pulling data from API POST response

Topic Labels: Scripting
Solved
Jump to Solution
4740 9
cancel
Showing results for 
Search instead for 
Did you mean: 
auekk2787
7 - App Architect
7 - App Architect

I'm running an API POST script and I'm trying to utilize the id that is returned in the response.

This is the key piece of the script. 

var postOptions = {
  method: 'POST',
  headers: myHeaders,
  body: formdata,
  redirect: 'follow'
};

let response = await remoteFetchAsync("https://xyz.com/...", postOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

I get this response. I'd like to then reference that id returned.

CONSOLE.LOG
"{"id":29644,"progress":0,"current_line":null,"status":"created","created_at":"2023-09-12T09:30:39-07:00","started_at":null,"ended_at":null,"file_url":null}"

I've tried this, but I get an undefined error.

console.log(response.result.id)

 

1 Solution

Accepted Solutions
Sho
11 - Venus
11 - Venus

How about this?

let response = await remoteFetchAsync("https://xyz.com/...", postOptions)
  .then(response => response.json())
  .catch(error => console.log('error', error));

console.log(response.id);

See Solution in Thread

9 Replies 9
Bill_French
17 - Neptune
17 - Neptune

If you retrieve the response as "text" you must parse the result. Alternatively, you could retrieve the response as "json" and avoid this step.

console.log(JSON.parse(result).id)

 

I'm getting an error - 

ReferenceError: result is not defined

console.log(JSON.parse(response).id)

Now error SyntaxError: "undefined" is not valid JSON

Sho
11 - Venus
11 - Venus

How about this?

let response = await remoteFetchAsync("https://xyz.com/...", postOptions)
  .then(response => response.json())
  .catch(error => console.log('error', error));

console.log(response.id);

Yes that's it! Nice catch.

I tried to give you the hint the day you asked, hoping you'd lean into it and solve it independently. Often, when forced to work through the problem to resolve it, you will understand more about the underlying elements.

Bill_French_0-1694621707338.png

 

Thanks. I'm pretty new to JS and I didn't catch I needed to change the reponse.text() to json() above. 

Yep - it takes about 5,000 hours to become proficient. Possibly helpful - ChatGPT. It’s not perfect but neither are we.