Coder Social home page Coder Social logo

renderjson's Introduction

Renderjson

Render JSON into collapsible, themeable HTML. This library aims to be very simple with few options and no external dependencies. It's aimed at debugging but you can use it wherever it is useful.

The code renders the JSON lazily, only building the HTML when the user reveals the JSON by clicking the disclosure icons. This makes it extremely fast to do the initial render of huge JSON objects, since the only thing that renders initially is a single disclosure icon.

Live Example

A live example can be found here.

Example

<div id="test"></div>
<script type="text/javascript" src="renderjson.js"></script>
<script>
    document.getElementById("test").appendChild(
        renderjson({ hello: [1,2,3,4], there: { a:1, b:2, c:["hello", null] } })
    );
</script>

Usage

The module exports one entry point, the renderjson() function. It takes in the JSON you want to render as a single argument and returns an HTML element.

Options

There are a couple functions to call to customize the output:

renderjson.set_icons('+', '-');

Call set_icons() to set the disclosure icons to something other than "⊕" and "⊖".

renderjson.set_show_to_level(level);

Call set_show_to_level() to show different amounts of the JSON by default. The default is 0, and 1 is a popular choice. As a special case, if level is the string "all" then all the JSON will be shown by default. This, of course, removes the benefit of the lazy rendering, so it may be slow with large JSON objects.

renderjson.set_max_string_length(length);

Strings will be truncated and made expandable if they are longer than length. As a special case, if length is the string "none" then there will be no truncation. The default is "none".

renderjson.set_sort_objects(sort_bool);

Sort objects by key (default: false)

renderjson.set_replacer(replacer_function)
renderjson.set_property_list(property_list)

These are the equivalent of the JSON.stringify() replacer parameter. Mozilla's documentation has a good description of how this parameter works. See test.html for an example of what these can do.

renderjson.set_collapse_msg(collapse_function);

Accepts a function (len:number):string => {} where len is the length of the object collapsed. Function should return the message displayed when a object is collapsed. The default message is "X items".

These functions are chainable so you may do:

renderjson.set_icons('+', '-')
          .set_show_to_level(2)
        ({ hello: [1,2,3,4], there: { a:1, b:2, c:["hello", null] } })

Theming

The HTML output uses a number of classes so that you can theme it the way you'd like:

.disclosure    ("⊕", "⊖")
.syntax        (",", ":", "{", "}", "[", "]")
.string        (includes quotes)
.number
.boolean
.key           (object key)
.keyword       ("null", "undefined")
.object.syntax ("{", "}")
.array.syntax  ("[", "]")

Copyright and License

License: ISC

Copyright © 2013-2017 David Caldwell <[email protected]>

Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

renderjson's People

Contributors

almenon avatar caldwell avatar iamakulov avatar itslenny avatar mfa avatar mitar avatar sgrebnov avatar wulfsolter 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

renderjson's Issues

Truncated string is multiline

After a long string containing \n is truncated, these new lines are actually printed, causing the truncated link to be multi-line, while the original is single line (and showing \n)

Auto-unfold for small number of items

It would be great if we could set a limit for which arrays are automatically unfolded. We have a lot of results that can potentially have many items, but often only have one. Unfolding them by hand is a little tedious, so having a limit that tells the system to unfold if there are only less than n items would help a lot. This would work with show_to_level, so I would think it would make sense to unfold everything to the given level, if the number of items is less than the unfold_if_less_than value.

Thanks!

show_to_level overrides set_max_string_length

I would expect set_max_string_length to work regardless of the level set. For example, if a large paragraph comes along in the first level you would want to show the first part of the paragraph, but truncate the rest.

The description for max_string_length implies it works regardless of level:

Strings will be truncated and made expandable if they are longer than
length. As a special case, if length is the string "none" then there
will be no truncation. The default is "none".

Instead what happens is that if the string is in a shown level, the string is expanded by default.

`renderjson` variable leaks to global scope

Due to the way the module is exported, the renderjson identifier (and the IIFE it is initialized to) is leaked into the global scope. Declaring it as a variable first and then initializing it with the IIFE would prevent the leak, be trivial to do, and not break any existing code. I'm happy to put together a PR.

Show Expanded

Is there a way to initialize the JSON object with every node expanded?

Redefining `window` gives problems in IE9

Using var window gives a redeclaration error in IE9 (while, funnily enough, works OK in IE7):
image
Also, I'm not sure that declaration has any use, as the only line where window is used is already managed with (window||{}).
(part of the same might apply to var define and var module too, but they're not giving direct problems in IE9)

Duplicated double quote for string value

When printing string value in an object, it wrap the value with duplicated double quote. Following is the quick fix I put into my local copy:

file: renderjson.js line: 117

        if (typeof(json) == "string")
          if (json.length > max_string)
            return disclosure('"', json.substr(0,max_string)+" ...", '"', "string", function () {
                return append(span("string"), themetext(null, my_indent, "string", JSON.stringify(json)));
            });
          else
            return themetext(null, my_indent, typeof(json), json);

Issue on IE11

Hi !

renderjson doesn't seem to work on IE11.
Can you confirm ?

I get an error about the "assign" method not being supported.

I am running IE11 on win 10 with no "emulation" mode.

Thanks in advance

Feature Request - Add Setter For Indentation

e.g.
renderjson.set_indentation(2); // adjust space-count
or
renderjson.set_indentation(' '); // allow tabs or spaces
or
renderjson.set_indentation('space', 2); // self-explanatory
or...
infinite number of ways to implement this, please consider it.

switch to typescript

I recently converted python-shell to typescript, Also see my medium article. (cause every two-bit dev has to have a medium article now right? :P )

Eventually I want to implement #17 perserving open/close of nodes, but before I do that I would want to convert to typescript.

Not sure when I'll get around to this. After October or later probably.

Feature Request: Clickable url strings

This is not a bug but rather a feature request.

When a JSON is rendered, it will be great if the code could scan and if it finds a string starting with "http", then render that link as a clickable link.

Clickable links

Is there a way to use set_replacer to make links in the tree clickable?

For long strings as values, hide them until user expands them

Could you please implement similarly to how nested objects are collapsed that also for huge/long string values they are initially collapsed and then user can expand them? So I have an issue that some objects have really long strings. And it would be great if they would not be shown unless user requests that.

I was looking at the code but was unsure how to implement this.

License name?

Hi, I was wondering if your license was part of a named license. I was looking at using this library for a company project, and there's only some licenses I am allowed to use.

Copy JSON after it has rendered

Hi,

Is there any option available to copy the JSON text after it has rendered. I tried to copy that and there are special characters that also get copied that are not required.

Regards

Feature Request

This is an amazing tool, thank you for building it!

I'd like to be able to update the json structure dynamically and preserve which nodes are open or folded.

Perhaps by having a way to query for the currently 'open' nodes, and to pass that result in when generating the replacement HTML. The query result would have to be somewhat aware of the data content so that nodes not present after the update are ignored. This same mechanism could be used to give people fine grained control over which nodes are opened during the initial display.

Doesn't work on vuejs

Pulled it via npm.
// importing
import renderjson from 'renderjson/renderjson'
// template
<div v-html="performance_report" v-if="performance_report" > </div>
// executing on mount


mounted(){
            this.performance_report = renderjson({ hello: [1,2,3,4], there: { a:1, b:2, c:["hello", null] } });
       },
		// outputs ``{}`` without any errors

Cannot use it in NextJS

I have installed renderjson (npm i renderjson), and I have imported it

import renderjson from 'renderjson';

when using in my code:

const jsonElement = renderjson(myjson);

i have the following error:

react-dom.development.js:9126 Uncaught ReferenceError: renderjson is not defined

Feature request - disclosures on the left

Thanks for this wonderful tool. I preview large JSON docs and it would be better to have the disclosure on the left. This way, it is offset from the rest of the keys and you can quickly visualize which keys have children by looking at the left.

For example, I work with NodeRED, and they render objects using this type of disclosure:
image

If I look at the same object section using renderjson:
image

As you can see, it is harder to tell which keys have children. Thanks again!

TypeError: Cannot read property 'append' of null

Hi Dear,
I am trying to use your library and I am facing this problem.
Below is the code. Can you help me on this

angular.element(document).ready(function () {
renderjson.set_icons('+', '-');
renderjson.set_show_to_level(1);

    var jsonstuff =  document.querySelector("#json");
    console.log(jsonstuff);
    jsonstuff.append(
        renderjson( $scope.nsdJSON)
    );

});

truncation for too many items

It would be nice to have truncation paramater in case there are too many items. set_show_to_level is useful in this regard, but it doesn't cover cases in which there are too many items in the level that you normally want shown.

Just something like this would work:

.............................
..............................
154 items truncated +

Alternatively, you could go with the approach used in the chrome developer tools and summarize the items like so:

[ 0-100 ] +
[ 100-200 ] +
[ 200-300 ] +
etc.... increasing the scale with the number of items.

Bug? Folding multiline text

When text with new lines folded it draws \n\r as new lines
image

But when it unfolded it prints those escape codes as it is
image

Clearly it must be other way around

P.S. Sorry for bad English 😅

Allow custom indent depth

Would be nice if the indent could be adjusted

might try looking at this over the weekend, but I make no promises

Feature Request: For ReferenceId to an id field in the JSON. Make the referenceID field clickable to auto navigate to the element.

For example we have a json

{ 'subject' : { '$id':'123', 'name':'maths', 'desc':'some desc' }, 'students': [ { '$id':'1' 'firstName':'bob', 'lastName':'agent', 'subjects':[ { '$refId':123 'type':'subject' } ] } ] }

Here you can see the subject in student object has a referenceid to subject object. A feature to make the reference ID's clickable so we can auto navigate to the subject object instead of trying to search in a long rendered json.

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.