fake-api-backend
fake-api-backend copied to clipboard
The `images` field in the product data returned from the API is in an incorrect JSON format
JSON Format Issue with Image URLs
Description:
The images
field in the product data returned from the API is in an incorrect JSON format. For example, the image URLs are currently being returned as:
[
"[\"https://i.imgur.com/QkIa5tT.jpeg\"",
"\"https://i.imgur.com/jb5Yu0h.jpeg\"",
"\"https://i.imgur.com/UlxxXyG.jpeg\"]"
]
This formatting issue causes problems when parsing the JSON and prevents us from using the data correctly.
Proposed Solution:
Below is a workaround to handle this formatting issue and correctly parse the image URLs. This solution cleans up the JSON string and returns the image URLs in the correct format.
Workaround:
export function formatImageJson(data) {
if (Array.isArray(data)) {
return data.map((item) => formatImageJson(item));
} else if (data && typeof data === "object" && data.images) {
if (Array.isArray(data.images) && typeof data.images[0] === "string") {
// Check if the first element is a stringified array
if (
data.images[0].startsWith("[") &&
data.images[data.images.length - 1].endsWith("]")
) {
try {
// Join the array elements and parse as JSON
const joinedString = data.images.join(",");
data.images = JSON.parse(joinedString);
} catch (error) {
console.warn(
`Warning: Could not parse images JSON. Using original array. Error: ${error.message}`
);
}
}
// Remove any remaining quotes from individual URLs
data.images = data.images.map((url) => url.replace(/^"|"$/g, ""));
}
}
return data;
}
use like
// Function to fetch specific category by ID
export const fetchProductsByCategoryId = async (categoryId: number) => {
const response = await axios.get(
`${API_URL}/products/?categoryId=${categoryId}`
);
const products = formatImageJson(response.data);
return products;
};
Additional Information:
If you have any questions or need further assistance, please let me know. Thank you!