reduced-jade•2y ago
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!
1 Reply
reduced-jadeOP•2y ago
@NiKo any idea of what is going on?
Hi I managed to get it working, As Capture Response, I set "Response" here is the javascript that converts the json into a variable, if that helps someone. // Assuming 'apiResponse' contains your entire API response and is already parsed to an object
if (apiResponse && apiResponse.records) {
// Initialize an empty array to store each concatenated name and description
let descriptions = [];
// Iterate over each item in the records array
apiResponse.records.forEach((record, index) => {
// Concatenate the name and description with a specific format
let resultString =
Result ${index + 1}:\nName: ${record.name}\nDescription: ${record.description}
;
// Add this string to the descriptions array
descriptions.push(resultString);
// Optionally, add a separator line between results if not the last item
if (index < apiResponse.records.length - 1) {
descriptions.push("\n---\n");
}
});
// Join all descriptions (with separators) into a single string
combinedDescriptionsVar = descriptions.join('');
} else {
// Handle cases where apiResponse is not in the expected format
combinedDescriptionsVar = "Invalid response structure.";
}