sacred-emeraldS
Voiceflow2y ago
2 replies
sacred-emerald

Handling API response in JavaScript: extract and convert JSON data to a Variable

Hello,

I'm working on fetching data from an API using a POST request and have successfully received a JSON response. However, I'm encountering difficulties in processing this response to extract information and store it in a JavaScript variable for further use.

Here's the JSON provided by the API:


[
{'name': 'Binary Blossom', 'description': 'A floral scent with notes of jasmine and tech innovation.'},
{'name': 'Code Noir', 'description': 'A bold blend of leather and tobacco, ideal for evening events.'},
{'name': 'Pixel Pour Homme', 'description': 'A light aquatic fragrance with hints of sea spray and sandalwood.'}
]
After capturing the API response, I store it in a variable named apiResponse, as illustrated in the enclosed image and i get Object Object as result.

To process this data, I'm attempting to stringify the JSON and convert the results into another variable. Here's the function I've written for this purpose:

javascriptcode:

let combinedDescriptionsVar = null;

function processApiResponse(apiResponse) {
try {
if (Array.isArray(apiResponse)) {
combinedDescriptionsVar = apiResponse.map(item => ${item.name}: ${item.description}).join('\n');
} else {
combinedDescriptionsVar = "Invalid data format received.";
}
} catch (error) {
combinedDescriptionsVar = "Error processing API response.";
}
}
The problem is, the combinedDescriptionsVar variable always ends up being null after I run this function, regardless of the API response seemingly being correctly formatted and captured.

Could anyone provide insights into why this might be happening? Am I missing a step in properly stringifying the JSON or in some other part of the process? Is the issue related to the capture response / response?

Any advice or suggestions would be greatly appreciated. Thank you in advance for your help!
api-response.png
Was this page helpful?