서울 공공데이터를 활용한 프로젝트 중, json 형식을 사용해서 응답을 받던 api만 사용하다 XML 형식을 사용하는 api를 써야하는 상황이 생겼다.
그러다, xml을 바로 json 형식 객체로 변환해주는 모듈을 찾게 되었다.
이 모듈은 xml형식에 데이터를 json 객체 형태로 변환하거나, json의 텍스트로 변환해준다.
또는 json을 xml로 변환해주는 반대의 동작도 지원해준다.
npm 사이트 : https://www.npmjs.com/package/xml2json
npm install xml2json
var parser = require('xml2json');
//ES6
import { toJson, toXML } from 'xml2json'
parser.toJson(xml, options);
let options = {
object: false,//반환할 json형식이 객체인지, 문자열인지
reversible: false,
coerce: false,
sanitize: true,
trim: true,
arrayNotation: false,
alternateTextNode: false
} //JSON 형식으로 반환할때 추가하는 옵션들
parser.toXml(json);
서울 실시간 도시데이터 API는 응답을 xml로 주시는데 이를 JSON으로 성공적으로 변환하여 콘솔에 찍어보았다.
import { API_URL } from "../static/API_config.js"
import { toJson } from 'xml2json';
import fetch from 'node-fetch';
//장소별 실시간 정보 + XML 파싱 to JSON
export const fetchLiveData = async (placeName) => {
const response = await fetch(API_URL(placeName))
.then((res) => res.text())
.then((xml) => toJson(xml, {
object: true, //반환값 object로 변환
reversible: false,
coerce: false,
sanitize: true,
trim: true,
arrayNotation: false,
alternateTextNode: false
}))
.then((obj) => {
const seoulcitydata = Object.values(obj)[0]
console.log(seoulcitydata.CITYDATA.LIVE_PPLTN_STTS);
})
return response;
}```