简体   繁体   English

在Javascript中创建可折叠的json树结构

[英]Creating collapsible json tree structure in Javascript

I have written javascript code which takes the file with a json entry as an input and generates tree structure for same. 我已经编写了JavaScript代码,该文件将带有json条目的文件作为输入并为其生成树结构。 Following is the fiddle for same : 以下是相同的小提琴:

https://jsfiddle.net/rishi007bansod/wk8nx21t/63/ https://jsfiddle.net/rishi007bansod/wk8nx21t/63/

you can test it by giving the following file as an input 您可以通过提供以下文件作为输入来进行测试

https://jsoneditoronline.org/?id=fd7cf89cd7f3469dbcd318575a86d7cc https://jsoneditoronline.org/?id=fd7cf89cd7f3469dbcd318575a86d7cc

Now I want to make this tree structure collapsible so that nodes in this json can expand/collapse. 现在,我想使该树结构可折叠,以便此json中的节点可以展开/折叠。 For implementing this I am referring code at: 为了实现这一点,我在以下位置引用代码:

Basic Collapsible 基本可折叠

I have also tried using this basic collapsible feature, following is the code for same : 我也尝试使用此基本可折叠功能,以下是相同的代码:

HTML 的HTML

<script type="text/ng-template"  id="tree_item_renderer.html">

    <button data-toggle="collapse" data-target="#demo">{{data.name}}</button>
    <button ng-click="add(data)">Add node</button>
    <button ng-click="delete(data)" ng-show="data.nodes.length > 0">Delete nodes</button>


    <div id="demo" class="collapse">
    <ul>
        <li ng-repeat="data in data.nodes" ng-include="'tree_item_renderer.html'"></li>
    </ul>
    </div>
</script>

<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>

<ul ng-app="Application" ng-controller="TreeController">

    <li ng-repeat="data in tree" ng-include="'tree_item_renderer.html'"></li>

</ul>

JavaScript 的JavaScript

angular.module("myApp", []).
controller("TreeController", ['$scope', function($scope) {
    $scope.delete = function(data) {
        data.nodes = [];
    };
    $scope.add = function(data) {
        var post = data.nodes.length + 1;
        var newName = data.name + '-' + post;
        data.nodes.push({name: newName,nodes: []});
    };


    $scope.tree = [{name: "myTree", nodes: []}];


    var json;




    function flatObject(obj,myTree) {
    console.log('==========tree length is: ' + myTree.length)
    var count = 0;
    Object.keys(obj).forEach(y => {
        console.log('key: ' + y)

                if (obj[y] instanceof Object) {
          //for(var j = 0; j < myTree.length; j++) 
          {
                console.log('printing key: ' + y+", value :"+obj[y])
              myTree.nodes.push({name: y,nodes: []});
              console.log('tree length: ' + myTree.length)
              flatObject(obj[y], myTree.nodes[count]);

          }
        } else {
           //for(var j = 0; j < myTree.length; j++) 
           {
                console.log('....printing key: ' + y+", value :"+obj[y])
                myTree.nodes.push({name: y,nodes: [{name: obj[y], nodes: []}]});
                console.log('value: ' + obj[y])
              console.log('tree length: ' + myTree.length)
           }
        }
        count++;
    });
}

    document.getElementById('files').addEventListener('change', handleFileSelect, false);

    function handleFileSelect(evt) {
      var files = evt.target.files; // FileList object

      // files is a FileList of File objects. List some properties.
      var output = [];
      for (var i = 0, f; f = files[i]; i++) {
        var reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (function (theFile) {
          return function (e) {
            console.log('e readAsText = ', e);
            console.log('e readAsText target = ', e.target);
            try {
              json = JSON.parse(e.target.result);
              var myTree = [{name: "my_Tree", nodes: []}];

              flatObject(json,myTree[0]);
              $scope.$apply(function() {
                $scope.tree = myTree;
              });

              alert('json global var has been set to parsed json of this file here it is unevaled = \n' + JSON.stringify(json));
            } catch (ex) {
              alert('ex when trying to parse json = ' + ex);
            }
          }
        })(f);
        reader.readAsText(f);
      }

    }

    document.getElementById('files').addEventListener('change', handleFileSelect, false);


}]);

CSS 的CSS

ul {
  list-style: circle;
}

li {
  margin-left: 20px;
}

Following is the fiddle for above code, 以下是上面代码的小提琴,

https://jsfiddle.net/rishi007bansod/wk8nx21t/65/ https://jsfiddle.net/rishi007bansod/wk8nx21t/65/

But it is not working as expected ie I am unable to expand and collapse nodes in json tree. 但是它没有按预期工作,即我无法在json树中展开和折叠节点。 How can I correct this code? 如何更正此代码?

Adding following dependencies in my project, mentioned in the link Bootstrap CDN solved my issue, Bootstrap CDN链接中提到的在我的项目中添加以下依赖项解决了我的问题,

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM