Skip to content

Command-line treeview generator for json-data originating from file or web

Notifications You must be signed in to change notification settings

nostradomus/JSON_treeview_generator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JSON treeview generator

What

This command-line tool converts JSON-data into a text-based treeview. The JSON-data can be originating from either a (local) file or directly from a web-api.

Why

When learning a new programming language, I prefer writing code which can actually serve in the future, instead of just writing hello world's. So, the language being PHP, I considered some web-related tool to be interesting enough.

How

The code for this script has been written in PHP on MacOS High Sierra on the built-in PHP version 7.1. It has been tested in parallel on a Raspbian Stretch with PHP 7.0. The script only uses PHP built-in functionalities. As such, there are no references to any external libraries.

The script loads JSON-data from either a file or a web-source. A recursive function iterates over the data, and outputs a human-readable text-based treeview. More details are to be found in the code section

Progress status

How to use it

The script can either be started by passing it as an argument to the php interpreter

$ > php jsonTreeview.php [required arguments] {options}

or directly as an application

$ > ./jsonTreeview.php [required arguments] {options}

The script contains a shebang on the first line which is optimised for linux based OS's. For other OS's, it might be necessary to replace #!/usr/bin/php by #!/usr/bin/env php. Do not forget to make the script executable :

$ > chmod +x jsonTreeview.php

In case that your generated treeview counts more lines than your console buffer can handle, it might be a good idea to dump the output to a file :

$ > php jsonTreeview.php [required arguments] {options} > myTreeviewOutput.txt

Starting the application with the --help option as argument will display the concerning linux man page. Always refer to the man page which is generated by the script you are running for the most relevant instructions (i.e. specific availability of options for the version you are running).

$ > php jsonTreeview.php --help

JSON TREEVIEW GENERATOR (1)            General Commands Manual            JSON TREEVIEW GENERATOR (1)

NAME
       jsonTreeview - generate a text-based treeview for json-data originating from file or web

SYNOPSIS
       jsonTreeview [-h]
       jsonTreeview [-v]
       jsonTreeview [-f file] {--valueonly}
       jsonTreeview [-u url] {--valueonly}

DESCRIPTION
       jsonTreeview is a tool to generate text-based treeviews for json-data originating
       from either a file or a web-API.

       Options -f and -u, followed by either a path/filename or a web-address, will allow
       the tool to go get the json-data to transform into a text-based treeview, as
       displayed below :

       http://www.thewebaddress/data.json or /pathname/filename.json
             |_firstelementkey
                |_firstdatalinekey : 1234
                |_seconddatalinekey : abcde
                |_...
             |_secondelementkey
                |_firstdatalinekey : 5678
                |_seconddatalinekey : fghij
                |_...
             |_...

       The root tag of the treeview will refer to the origin of the json-data.
       Collection headers will display the key as label.
       Branch ends will display key/value pairs.

       When adding the --valueonly option to the commandline, a treeiew with only element values
       will be generated (no key labels). Collection headers will be labeled ARRAY.

       The -h option will display this help text.

       The -v option will display the tools software version number.

OPTIONS
       -h -H --help           display this help message
       -v -V --version        display this application's version
       -f -F --file           generate a treeview from the json-data in the file
       -u -U --url            generate a treeview from the json-data retrieved from the url
             --valueonly      generate a treeview with values only (no key labels)

DIAGNOSTICS
       Informative messages will be displayed when the application is called in
       an incorrect way (i.e. missing/unkown/invalid parameters)

AUTHOR
       This tool was created by The Nostradomus Engineering Team, for quick analysis
       of json-data from web-APIs. We can be contacted through
       http://nostradomus.ddns.net/contactform.html for any questions.

Technical details

Programming language

The code has been written in PHP. The minimum required version is PHP 5.3, due to the use of HereDoc/NowDoc. The script has however been tested to work correctly up to version 7.

Code

The full source code is available in the source folder :

version name description
v1.0.0.0 jsonTreeview.php initial version

Snippets

Retrieving the data

The retrieval of the JSON-data is handled in the main-loop block of the script. In the below pseudo-code block, only the iterateArray-function is shown. In the actual source-code, an if/then/else will choose between different types of output depending on the --valueonly option.

$file = $argv[2];                                            // get the path/filename or url-address from the arguments list
$json = file_get_contents($file);                            // get the json-data   
$json = json_decode($json, true, 512, JSON_OBJECT_AS_ARRAY); // decode the json-data to an array
$jsonTree = "$file".PHP_EOL;                                 // create the root of the json tree
$jsonTree = $jsonTree.iterateArray($json,1);                 // iterate through the tree, and append all elements in branches (keys and values)
echo $jsonTree;                                              // send the result to the output

Building the treeview with recursion

The standard recursive function which will output the treeview takes to arguments :

  • $dict : the dictionary/collection/array with the key/value pairs to process
  • $level : the branch depth-level of the root element of $dict

When iterating, the keys (or labels) will be preceded with the appropriate branch lines. When the value associated to a key concerns a list (one more level down), only the key will be added to the treeview, and the function will recursively call itself to 'dig deeper' in the data. When an end element is detected, both the key and the value will be added to the treeview.

The output of the function is a multiline string.

// recursive iterator to build a text-based treeview with key/value pairs
function iterateArray($dict,$level) {
    $spaces = '';
    for ($i = 0; $i <= ($level*3); $i++) {
        $spaces = $spaces.' ';
      }
    $branch = '';
    foreach($dict as $key => $value) {
        if (!(is_array($value))) {
          $indent = '';
          for ($i = 0; $i <= (strlen($key)+3); $i++) {
              $indent = $indent.' ';
            }
          $value = str_replace("\n","\n ".$spaces.$indent,$value);
          $branch = $branch.$spaces."|_".$key." : ".$value.PHP_EOL;
          } else {
              $next = iterateArray($value,($level+1));
              $branch = $branch.$spaces."|_".$key.PHP_EOL.$next;
             }
    }
    return $branch;
  }

When adding the --valueonly options to the command-line arguments list, and alternative function is called, which is based on a PHP built-in iterator and treeview generator. This function only takes the data-collection as an argument.

This function outputs a similar type of multiline string, with a slightly different layout, and only values as data.

// value-only treeview generator based on language built-in iterators
function iterateValues($dict) {
    $tree = '';
    $json2list = new RecursiveArrayIterator($dict);
    $list2tree = new RecursiveTreeIterator($json2list);

    foreach( $list2tree as $key => $value ) {
        $tree = $tree.$value.PHP_EOL;
    }
    return $tree;
  }

Contributors

If you are having any good suggestions, just drop me a line 📧. If feasible, I'll be happy to implement any proposed improvements. And if you are having lots of time, I'll be happy to share the work with you ;-).

When you create your own version, don't forget to tell us about your work. We'll be happy to publish a link in the 🎊Hall of Fame🎊.

🌐 License

At this moment, there is no specific license attached to this project.

So, today, if you like it, have fun with it (at your own risk of course :-D), and especially, be creative.

Oh, and when using anything from this repository, it is highly appreciated if you mention its origin.

If you would like to use any of this work (or the whole project) for commercial use, first contact us 📧, so we can add the appropriate license, which best fits your business.

Releases

No releases published

Packages

No packages published

Languages