박주영

xml을 json으로 변환하기

1 -let request = require('request'); 1 +var express = require('express');
2 +var request = require('request');
2 3
3 -// REST API 경로 & 요청 메시지 4 +//xml을 json으로 바꾼다.
4 -const url = 'http://apis.data.go.kr/1470000/FoodAdtvInfoService/getFoodAdtvInfoList?ServiceKey='; 5 +const convert = require('xml-js');
5 6
6 -//api key 7 +var url = 'http://apis.data.go.kr/1470000/FoodAdtvInfoService/getFoodAdtvInfoList';
7 -const key = 'ofY2ppOq5kBqT5jYPaGsW%2BEy7OR5a1bf5Z9PHvqNKvwO5DSCaU2x2qCj%2FoXnuB1YVbMTlErkHWSMEsR5b7isrw%3D%3D'; 8 +var key ='PFs%2BxbmfLdZwXaK7l5l9w4xEcdaDcYByiEj9PoHq2KCPAtx%2FE1N7OPUaCPr6bam18nVQgKOnuxMlaRsJhG6gyQ%3D%3D';
8 - 9 +var queryParams = '?' + encodeURIComponent('ServiceKey') + '=' +key;
9 -//REST(URL)
10 -const complete_url = url +key ;// '&numOfRows=2&pageNo=2';
11 -
12 -console.log(complete_url);
13 -
14 -request(complete_url, function(error, response, body){
15 - if(!error && response.statusCode ==200)
16 - console.log(body);
17 -})
18 -
19 -
20 -/*
21 queryParams += '&' + encodeURIComponent('prdlst_cd') + '=' + encodeURIComponent('C0118010300000'); 10 queryParams += '&' + encodeURIComponent('prdlst_cd') + '=' + encodeURIComponent('C0118010300000');
22 queryParams += '&' + encodeURIComponent('pc_kor_nm') + '=' + encodeURIComponent('과.채음료'); 11 queryParams += '&' + encodeURIComponent('pc_kor_nm') + '=' + encodeURIComponent('과.채음료');
23 queryParams += '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent('1'); 12 queryParams += '&' + encodeURIComponent('pageNo') + '=' + encodeURIComponent('1');
24 queryParams += '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent('3'); 13 queryParams += '&' + encodeURIComponent('numOfRows') + '=' + encodeURIComponent('3');
25 -*/
26 -
27 14
28 -/*
29 -예제코드
30 request({ 15 request({
31 url: url + queryParams, 16 url: url + queryParams,
32 method: 'GET' 17 method: 'GET'
33 }, function (error, response, body) { 18 }, function (error, response, body) {
19 + if(error){
20 + console.log('에러입니다.')
21 + }
22 + else{
23 + if(response.statusCode ==200)
24 + var result =body;
25 + var xmltojson = convert.xml2json(result,{compact:true,spaces:4});
26 + console.log(xmltojson);
27 + }
34 //console.log('Status', response.statusCode); 28 //console.log('Status', response.statusCode);
35 //console.log('Headers', JSON.stringify(response.headers)); 29 //console.log('Headers', JSON.stringify(response.headers));
36 //console.log('Reponse received', body); 30 //console.log('Reponse received', body);
37 -}); 31 +});
38 -*/
39 -
40 -// module.exports.이름 = 함수;
...\ No newline at end of file ...\ No newline at end of file
......