
1. 개요
Node.js에서 json 파일을 직접 불러와서 사용해 보는 예제이다.
2. 사용법
JSON은 JavaScript Object Notation의 약자로 데이터를 전송하는 데 사용한다.
JSON은 key와 value로 구성되어 있다.
아래는 무지개의 영어를 키로 하고 한글을 값으로 하는 JSON 파일이다.
파일 이름 : hello-rainbow.json
{
"red" : "빨강",
"orange" : "주황",
"yellow" : "노랑",
"green" : "초록",
"blue" : "파랑",
"indigo" : "남색",
"violet" : "보라"
}
이번 예제에서는 별도의 모듈이 필요하지 않는다.
아래와 같이 json 파일을 직접 읽어 json.red 를 출력하면 "빨강"이 표시된다.
var json = require('./hello-rainbow.json');
console.log(json.red);
JSON.stringify() 함수는 JSON을 문자열로 변환한다.
var text = JSON.stringify(json);
JSON.parse() 함수는 문자열을 JSON 개체로 변환한다.
var jsonObj = JSON.parse(text);
3. 예제
아래는 json 파일을 읽고 문자열로 변환하고 다시 JSON 객체로 변환하는 코드이다.
var json = require('./hello-json-load.json');
console.log(json);
console.log(json.red);
console.log(json.orange);
// JSON 객체를 JSON 문자열로 변환한다.
var text = JSON.stringify(json);
console.log(text);
// JSON 데이터를 JSON 객체로 변환한다.
var jsonObj = JSON.parse(text);
console.log(jsonObj.green);
console.log(jsonObj.blue);
실행 결과
{ red: '빨강',
orange: '주황',
yellow: '노랑',
green: '초록',
blue: '파랑',
indigo: '남색',
violet: '보라' }
빨강
주황
{"red":"빨강","orange":"주황","yellow":"노랑","green":"초록","blue":"파랑","indigo":"남색","violet":"보라"}
초록
파랑
아래는 json 파일을 읽어 파일로 저장하고 다시 JSON 파일을 읽어 JSON 객체로 변환하는 코드이다.
var jsonFile = require('./hello-rainbow.json');
var fs = require('fs');
var rainbowJson = JSON.stringify(jsonFile);
fs.writeFileSync("hello-parsed.json", rainbowJson)
var data = fs.readFileSync("hello-parsed.json")
var json = data.toString();
console.log(json);
var parsedJson = JSON.parse(json);
console.log(parsedJson);
실행 결과
{"red":"빨강","orange":"주황","yellow":"노랑","green":"초록","blue":"파랑","indigo":"남색","violet":"보라"}
{
red: '빨강',
orange: '주황',
yellow: '노랑',
green: '초록',
blue: '파랑',
indigo: '남색',
violet: '보라'
}
728x90
'■ Front-End ■ > Node.js' 카테고리의 다른 글
[Node.js] http 모듈 - 요청 URL에 따른 다양한 서비스 (0) | 2023.02.26 |
---|---|
[Node.js] http 모듈로 웹으로 GET/POST를 서비스해보자. (0) | 2023.02.26 |
[Node.js] http 모듈로 text와 html을 브라우저에 표시해보자. (0) | 2023.02.26 |
[Node.js] socket.io 모듈을 사용하여 소켓통신을 구현해 보자. (0) | 2023.02.26 |
[Node.js] net 모듈을 사용하여 네트워킹을 해보자. (0) | 2023.02.26 |
댓글