1
0

More than 1 year has passed since last update.

誰でも作れるBetterJSONトランスパイラを作ってみる

Last updated at Posted at 2022-12-25

概要

(厳密な)JSONはイメージとは裏腹に手で書くには思ったより不便な仕様になっています。

  • コメントが書けない。
  • Trailing comma(末尾のカンマ) は認められていない。(=手で追加する際にカンマを意識する必要が出て面倒)
  • (ダブルコーテーションの代わりに)シングルコーテーションは使えない。
  • キー名もダブルコーテーションで囲む必要がある。

などなど・・・

というわけで、JavaScriptのオブジェクト表記のようにゆるく書けてなおかつそのままJSONに変換できるトランスパイラを作ってみる。

誰でも作れる

ちょこっとコードを付けてeval(new Function)してJSON.stringifyで出力するだけです。

node.jsなら追加のモジュール一切不要で実現できます。

bjson.js
const fs = require('fs');

if(process.argv.length < 3) {
    const path = require('path');
    jsfile = path.basename(process.argv[1]);
    console.log('usage: node ' + jsfile + ' [-p] srcpath [outpath]');
    process.exit(-1);
}

try {
    var pos = 2;
    var pretty = false;

    for (let i = 2; i < process.argv.length; i++) {
        if(process.argv[i].indexOf('-') === 0) {
            if(process.argv[i].charAt(1).toLowerCase() === 'p') {
                pretty = true;
            }
            pos += 1;
        } else {
            break;
        }
    }

    let filedata = fs.readFileSync(process.argv[pos]);

    let prettycode = pretty ? ', null, 2': '';

    let code = 'let jsondata = ' + filedata + '; let result = JSON.stringify(jsondata' + prettycode + '); return result;';

    let result = new Function(code)();

    if(process.argv.length <= pos + 1) {
        console.log(result);
    } else {
        fs.writeFileSync(process.argv[pos+1], result);
    }
} catch (err) {
    console.error(err.message);
    process.exit(1);
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0