[ReactNative] xml2js ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋กœ XML to JSON ํ•˜๊ธฐ
728x90

Today, What I learned?

ํ”„๋กœ์ ํŠธ ์ค‘!.. api์—์„œ ๊ฐ€์ ธ์˜ค๋Š” xml ๋ฐ์ดํ„ฐ๋ฅผ JSON ๋ฐ์ดํ„ฐ๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ ์œ„ํ•ด ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ณผ์ •์„ ์ •๋ฆฌํ•ด ๋ณธ๋‹ค.

๋จผ์ € ์‚ฌ์šฉํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋Š” ์ด๊ฒƒ์ด๋‹ค.

https://github.com/connected-io/react-native-xml2js

 

GitHub - connected-io/react-native-xml2js: XML to JavaScript object converter.

XML to JavaScript object converter. Contribute to connected-io/react-native-xml2js development by creating an account on GitHub.

github.com

 

 

๋ณ€ํ™˜ํ•˜๊ธฐ

const parseString = require('react-native-xml2js').parseString;

export const getBoxOffice = () =>
  fetch(
    `${BASE_URL}/boxoffice?service=${API_KEY}&ststype=day&date=${getYesterdayString()}&catecode=GGGA&area=11`
  )
    .then((res) => res.text())
    .then((data) => {
        const cleanedString = data.replace('\ufeff', '');
      let boxOfficeData;
      parseString(cleanedString, (err, result) => {
        if (err !== null) {
          console.log('error: ', err);
          return;
        }
        boxOfficeData = JSON.parse(JSON.stringify(result));
      });
      return boxOfficeData;
    })
    .catch((error) => console.log(error));

ํŒจ์น˜ํ•ด์™€์„œ parseString ํ•จ์ˆ˜๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ํŒŒ์‹ฑ ํ•œ๋‹ค.

featch ํ•จ์ˆ˜ ์•ˆ์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ฆฌํ„ดํ•ด์ฃผ๋Š” ๊ฒƒ์„ ๊ผญ ์žŠ์ง€ ๋ง์ž!..

 

๊ฒฐ๊ณผ๋ฌผ์€ ์•„๋ž˜์™€ ๊ฐ™๋‹ค. ์ด์ œ ์ด ๋ถ€๋ถ„์—์„œ boxofs, boxof์•ˆ์œผ๋กœ ๋“ค์–ด๊ฐ€์„œ ๋ฐ์ดํ„ฐ๋ฅผ ๋ Œ๋”๋ง ํ•˜๋ฉด.. ๐Ÿฅบ

 

 

Non-whitespace before first tag

 const cleanedString = data.replace('\ufeff', '');

์š” ๋ถ€๋ถ„์€ Non-whitespace before first tag ๋ผ๋Š” ์—๋Ÿฌ๊ฐ€ ๋– ์„œ ๋„ฃ์–ด์ฃผ์—ˆ๋‹ค.
fetch ํ•ด์˜จ xml ๋ฐ์ดํ„ฐ์—์„œ ๊ณต๋ฐฑ์„ ์—†์• ์ฃผ๋Š” ์ฝ”๋“œ๋‹ค.

๊ทธ๋ฆฌ๊ณ  ์ € ํ•จ์ˆ˜๋ฅผ parseString ํ•จ์ˆ˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ๋„ฃ์–ด์ฃผ๋ฉด ๋œ๋‹ค.

 

 

 

xml ๋ฐ์ดํ„ฐ๋ฅผ json์œผ๋กœ ๋ฐ”๊พธ๊ธฐ.. ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ๋•์— ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ๋‹ค! (๋งˆ๋ƒฅ ์‰ฝ์ง€ ์•Š์•˜์Œ..)

 

 

728x90