人気ブログランキング | 話題のタグを見る
JSONファイルにコメントをつけたい場合どうするか?
概要
JSONファイルにコメントをつけたい場合どうするか?

対処案1
データにコメントを混ぜる


{
"id":1,
"text":"test",
"comment": "このデータはhogeです"
}


対処案2
コメント行を自力で抜く


// 参考 https://github.com/lorenwest/node-config/blob/master/lib/config.js
var fs = require('fs');
console.log(readJson('/share/test.json'));

function readJson(fullFilename) {
var fileContent;
try {
fileContent = fs.readFileSync(fullFilename, 'UTF-8');
} catch (e2) {
throw new Error('Config file ' + fullFilename + ' cannot be read');
}
var configObject = JSON.parse(_stripComments(fileContent));
return configObject;

function _stripComments(fileStr) {

var uid = '_' + +new Date(),
primitives = [],
primIndex = 0;

return (
fileStr

/* Remove strings */
.replace(/(['"])(\\\1|.)+?\1/g, function(match){
primitives[primIndex] = match;
return (uid + '') + primIndex++;
})

/* Remove Regexes */
.replace(/([^\/])(\/(?!\*|\/)(\\\/|.)+?\/[gim]{0,3})/g, function(match, $1, $2){
primitives[primIndex] = $2;
return $1 + (uid + '') + primIndex++;
})

/*
- Remove single-line comments that contain would-be multi-line delimiters
E.g. // Comment /* <--
- Remove multi-line comments that contain would be single-line delimiters
E.g. /* // <--
*/
.replace(/\/\/.*?\/?\*.+?(?=\n|\r|$)|\/\*[\s\S]*?\/\/[\s\S]*?\*\//g, '')

/*
Remove single and multi-line comments,
no consideration of inner-contents
*/
.replace(/\/\/.+?(?=\n|\r|$)|\/\*[\s\S]+?\*\//g, '')

/*
Remove multi-line comments that have a replaced ending (string/regex)
Greedy, so no inner strings/regexes will stop it.
*/
.replace(RegExp('\\/\\*[\\s\\S]+' + uid + '\\d+', 'g'), '')

/* Bring back strings & regexes */
.replace(RegExp(uid + '(\\d+)', 'g'), function(match, n){
return primitives[n];
})
);
};
}



by mima_ita | 2014-06-18 19:56 | node.js
<< jasmine-nodeのXM... Node.jsでIPv6を扱う >>



実験ですお

by mima_ita
検索
カテゴリ
最新の記事
.NET4.5におけるasy..
at 2014-07-02 00:46
.NETでTwitterを検..
at 2014-06-29 00:49
Redmineのプラグインで..
at 2014-06-28 03:29
IO.popenのwrite..
at 2014-06-28 03:25
RedmineのWikiでU..
at 2014-06-28 03:16
以前の記事
最新のトラックバック
その他のジャンル
ブログパーツ