Giter Site home page Giter Site logo

summerstyle / jsontreeviewer Goto Github PK

View Code? Open in Web Editor NEW
308.0 10.0 98.0 60 KB

json formatter/viewer/pretty-printer (with jsonTree javascript-library)

Home Page: http://summerstyle.github.io/jsonTreeViewer

License: MIT License

HTML 18.82% CSS 6.31% JavaScript 74.87%
json jsontree-library json-tree lightweight vanilla-js library viewer pure-javascript

jsontreeviewer's People

Contributors

summerstyle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jsontreeviewer's Issues

AngularJS Directive

this is not a bug, but a contribution.
I made an angularjs directive for this.

.directive('jsonTree', function () {
     return {
         restrict: 'EA',
         scope: {
             data: '=',
             expandall: '&',
             collapseall: '&'
         },
         template: '<div></div>',
         link: function ($scope, element, attrs) {
             var tree;
            tree = jsonTree.create($scope.data, element[0]);
         } 
     }
 });

html syntax:
<div json-tree data="inspector.reqbody">Invalid json-data, check RAW format</div>

data is the json object.

obviously collapseall and expandall functionality is not there yet, but this is a good starting point

findAndHandle ?

The readme has no mention of the findAndHandle method, and what the matcher, or handler functions need to be, or contain.

Could you provide some example or definition for that? Thanks

Values are not selectable.

This control would be particularly useful for developers. Developers are power users. Developers get annoyed when the values that they're working with have to be typed out manually instead of copied and pasted.

Parent count

Just a suggestion, I dont know how to make it on github. When you want to open up to a certain level, it's not the number of children that counts, it's the number of parents. There should be something the developper could write like this:

tree.expand(function(node) {
   return node.parents.length < depth;
}

Here's a working thing that you can easily include in your source code like parents() with a "s" or something:

var get_nb_parents = function(node) {
    var n = node,
        retour = 0;
    while (n.parent !== null) {
        n = n.parent;
        retour++
    }
    return retour;
};
tree.expand(function (node) {
    return get_nb_parents(node) < max_level;
});

Some better things

  • separate the tree library (tree.css, tree.js)
  • replace ids in css with classes (because it is possible to add two trees at one page)
  • add library docs
  • replace an icon with beautiful one
  • add support for color themes
  • refactor CSS-styles for tree. Class names should be more specifiсally, because now it is a library, and it may use in various pages, including pages with same class names. And now, markup is ugly(
  • add beautiful font 'PT Mono' from google.fonts
  • add feature with creation of filter function from textarea by new Function
  • add feature with selecting some nodes by filter function
  • add sorting for object keys
  • add highlighting for expanded nodes
  • add search by js-path (for ex. root["phoneNumbers"]["0"]["type"])
  • add displaing js-path for each node by click? And copy this path to search form (for editing path and finding similar or child nodes)
  • add expanding of root node by depth (count of descendants levels)
  • add expanding for all tree recursively by some function (for ex., expand all nodes with some count of children) Fix docs!
  • Add unit-tests for library
  • Add custom templates for values (by matcher + handler). For example:
  • strings which starts with "http://" displays as link
  • nodes with label "color" displays with circle of color in value at right side
  • numbers displays as "123 000 000" with spaces
  • nodes with label "image" by mouseover shows images preview
    etc.
  • Add "find and get as array" feature. Not nodes marks, only result displays as array.
  • Change app.js' styles and class names. Now this is very ugly!

autoload

with http://summerstyle.github.io/jsonTreeViewer#<url>

Doesn't escape HTML entities

jsonTree.js will print out HTML content to the page as is rather than escaping the HTML entities. This results in the HTML being inserted into the DOM and presented, and allows some types of custom Javascript execution. This constitutes an XSS vulnerability for any pages that render user-provided JSON using this library.

For example, on your demo page at http://summerstyle.github.io/jsonTreeViewer/ - provide the input {"test":"<img src='x' onerror='alert(1)'>"} and observe the alert.

Some ideas

Недавно установила это прекрасное расширение для лисы https://addons.mozilla.org/es/firefox/addon/json-dataview/
В нем используется моя библиотека, но был сделан ряд улучшений.
Хочу добавить этот функционал в саму библиотеку.

  • Для длинных строк - сделать правильные отступы (inline-block vs inline)
  • Если массив/объект не пустой - в середине показывать многоточие
  • Добавить поддержку горячих клавиш (+ с шифтом рекурсивно раскрыть)?
  • Если массив/объект пустой - не раскрывать его (это я сама придумала)
  • Добавить возможность редактирования значений, включая замену поддерева
  • Раскрывать при инициализации только ноды с определенными ключами?
  • Передавать функцию для вывода содержимого ноды (например, если это строка и начинается с http://, то вывести как ссылку, т.е. матчер+хендлер)
  • Добавить слева для объектов и массивов пунктирную линию для улучшения читабельности? Или при наведении менять фон?
  • Добавить флаг для нод, обозначающий возможное отсутствие этой ноды в итоговом json, сделать отображение полупрозрачным
  • Решить проблемы с производительностью при отрисовке действительно большого дерева !!!
  • Сделать подтипы для узлов (определяются при помощи матчера). Например, нода с именем url, типа 'строка' и начинающаяся с префикса http:// - это подтип 'ссылка' с соотв. шаблоном для вывода (с тегом <a> и подчеркнутая)

А также, идеи для редактора:

  • Добавить возможность отрисовывать сразу несколько json-деревьев (в этом случае как работать с верхним меню? Вариант - выделять одно из деревьев. Также можно сделать 2 галочки - для одновременное операции с деревьями)
  • Сделать возможным загружать json по url и из текстового файла?
  • Сделать фильтрацию узлов (для выделения их цветом)
  • Сделать сортировку по ключам
  • По галочке скрывать/показывать необязательные узлы
  • Ползунок для раскрытия дерева по уровням (сдвигаем - по одному уровню раскрывать узлы)

Big refactoring

CSS:

  • with prefix (jsontree- or jst-)
  • support color themes
  • good structure

JS constructors:

  • use templates
  • change inheritance

You've forgotten "recursive"

Your expand function wasn't 100% working. Here's a working version of your expand Tree function:

        /**
         * Expands all tree nodes (objects or arrays) recursively
         *
         * @param {Function | undefined} filterFunc - 'true' if this node should be expanded
         * @param {Object | undefined} node - starting node if precised
         */
        expand : function(filterFunc, node) {
            var self = this,
                n = (typeof(node) === 'undefined' ? this.rootNode : node);
            if (!n.isComplex) {
                return;
            }
            if (typeof(filterFunc) === 'function') {
                if (filterFunc(n)) {
                    n.expand();
                    n.childNodes.forEach(function(item) {
                        self.expand(filterFunc, item);
                    });
                } else {
                    n.collapse();
                }
            } else {
                n.expand();
                n.childNodes.forEach(function(item) {
                    self.expand(filterFunc, item);
                });
            }
        },

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.