'comment'에 해당되는 글 1건

  1. 2015.06.25 [node.js] json 파일 require 할때 주석(코멘트) 처리
Programming/node.js2015. 6. 25. 12:55


node.js v.0.5부터 json 파일 require()로 가져 올 수 있다.

그런데... 형식에 조금만 벗어나도 에러가 발생하는데.. 형식은... 잘 맞추면 되는데요..

문제는....주석을 넣어도 에러가 난다 orz 

( 당연히 다른 라이브러리나 file 읽어서 하는 방법도 있지만 기본 기능을 그대로 쓰고 싶음...)

$ vi test.js
var testJson = require('./test.json');
console.log(testJson);

$ vi test.json
{
    //comment test
    "key1":"test1",
    "key2":"test2",
}
$ node test.js
module.js:485
    throw err;
          ^
SyntaxError: /data/webroot/test.json: Unexpected token /
    at Object.parse (native)
    at Object.Module._extensions..json (module.js:482:27)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/data/webroot/test.js:1:78)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)


그래서 구글링 결과!!

http://stackoverflow.com/questions/244777/can-i-comment-a-json-file

{ //코멘트라는 키를 생성해버리면됨
   "_comment": "comment text goes here...",
   "glossary": {
{ //키명을 똑같이 해서 위에 설명을 넣어도될듯
  "api_host" : "The hostname of your API server. You may also specify the port.",
  "api_host" : "hodorhodor.com",

생각의 차이~!! 아래처럼 구분할 수있게 ㅎㅎ 어자피 해당 키는 안쓰면 되니까 ㅎㅎ

$ vi test.json
{
    "*****COMMENT*****" : "test comment",
    "key1":"test1",
    "*****COMMENT*****" : "test comment11",
    "key2":"test2",
    "*****COMMENT*****" : ""
}
$ node test.js
{ '*****COMMENT*****': '', key1: 'test1', key2: 'test2' }


Posted by 시니^^