Node.jsで、pathを持っているファイル名配列を Tree構造のjsonに変換する方法

はてなブックマーク - Node.jsで、pathを持っているファイル名配列を Tree構造のjsonに変換する方法
LINEで送る
Pocket

目次

ことの始まり

例えばこんな配列があります

[
'/aaa/bbb/file.txt',
'/aaa/bbb/ccc/file2.text',
'/aaa/vvv/mmm/file3.text',
'/ddd/ccc/file4.text',
'/ddd/ccc/file5.text'
]

これを、そのDirectory構造をそのまま反映するjsonのツリー構造にしたい場合がありますね!(きっとある!)

その時は、下記のプログラムで変換できちゃいます!

JavaScriptプログラム

このファイルを「flat2path2jsontree.js」とします。

var _ = require('lodash');
var paths = [
    '/FolderC/FolderA/FolderQ/ItemA',
    '/FolderC/FolderA/Item1',
    '/FolderD/FolderF/FolderM/ItemA',
    '/FolderD/FolderF/FolderM/ItemB',
    '/FolderD/FolderG/ItemD',
    '/ItemInRoot'
];

function pathString2Tree(paths, cb) {
    var tree = [];

    //ループする!
    _.each(paths, function (path) {
        // currentLevelを rootに初期化する
        var pathParts = path.split('/');
        pathParts.shift();
        // currentLevelを rootに初期化する
        var currentLevel = tree;

        _.each(pathParts, function (part) {

            // pathが既存しているかどうかをチェックする
            var existingPath = _.find(currentLevel, {
                name: part
            });

            if (existingPath) {
                // Pathはすでにツリー構造に入っているので、追加しない
                // current levelを下の子供階層に設定し直す
                currentLevel = existingPath.children;
            } else {
                var newPart = {
                    name: part,
                    children: [],
                }

                currentLevel.push(newPart);
                currentLevel = newPart.children;
            }
        });
    });

    cb(tree);
}
pathString2Tree(paths, function (tree) {
    console.log('tree: ', JSON.stringify(tree));
});

これを実行する前に、下記の操作も忘れないでくださいね。

npm install lodash --save

実行

それから

node flat2path2jsontree.js

これを実行した結果

ちょっと分かりやすいとは言えないですね。

jsonを整形してみましょう。

https://jsonformatter.curiousconcept.com/   (このサイトの信頼性を保証することでも推薦することでもありません、自己責任でご利用ください。)

ちょっとここにコピーして、整形しましょう。

補正

お!{“tree”:”ほんにゃらら”}の形を期待しているんですね、それが正しいです。

ちょっと補正してあげます。

そうすると、綺麗なツリー構造になりました!

もちろん、これをプログラムを修正すれば、できます!

そのやり方は皆さんの練習として、やってみてください!笑

まとめ

node.jsでtree構造のjsonファイルを作る時は

これを参考してできますね!

プログラムはこちらで、公開しました!ご参照ください。

他の言語も同じような原理で作ることができるはずです!

興味のある方はぜひやってみてください!

 

 

はてなブックマーク - Node.jsで、pathを持っているファイル名配列を Tree構造のjsonに変換する方法
LINEで送る
Pocket

Add a Comment

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close