diff --git a/src/hooks/useFetch.ts b/src/hooks/useFetch.ts index e16e756..82a6d3c 100644 --- a/src/hooks/useFetch.ts +++ b/src/hooks/useFetch.ts @@ -1,3 +1,4 @@ +import replaceTextProperties from '@/utils/extractInnermostValues'; import { useEffect, useState } from 'react'; import { xml2json } from 'xml-js'; @@ -17,7 +18,7 @@ export default function useFetch(url: string) { const response = await fetch(url); const xmlText = await response.text(); const jsonData = JSON.parse(xml2json(xmlText, { compact: true, spaces: 2 })); - setData(jsonData); + setData(replaceTextProperties(jsonData)); } catch (error) { console.error('Error fetching data:', error); } finally { diff --git a/src/utils/extractInnermostValues.ts b/src/utils/extractInnermostValues.ts new file mode 100644 index 0000000..962ba8a --- /dev/null +++ b/src/utils/extractInnermostValues.ts @@ -0,0 +1,35 @@ +/** + * 객체의 '_text' 속성을 해당 값으로 대체하는 함수 + * + * @template T - 입력 객체의 타입 + * @param {T} obj - 가장 안쪽의 값을 추출할 객체 + * @returns {T} '_text' 속성이 해당 값으로 대체된 입력 객체와 동일한 구조의 새로운 객체 + */ +export default function replaceTextProperties(obj: T): T { + if (typeof obj !== 'object' || obj === null) { + return obj; + } + + if (Array.isArray(obj)) { + return obj.map(replaceTextProperties) as unknown as T; + } + + if (obj && typeof obj === 'object' && '_text' in obj) { + const textValue = obj._text; + if (typeof textValue === 'string') { + const parsedValue = +textValue; + if (!isNaN(parsedValue)) { + return parsedValue as T; + } + } + return textValue as T; + } + + const result: { [key: string]: T[keyof T] } = {}; + + for (const [key, value] of Object.entries(obj)) { + result[key] = replaceTextProperties(value); + } + + return result as T; +}