Git Product home page Git Product logo

json2html's Introduction

json2html

Python module to convert JSON into a human readable HTML Table representation.

Latest Version Downloads CI codecov

Features

  • User friendly tabular format, easy to read and share.

  • If the value of the key is an array of objects and all the keys are the same (value of the key is a dict of a list), the module will club by default. E.g.:

    input = {
        "sampleData": [{
            "a":1, "b":2, "c":3
        }, {
            "a":5, "b":6, "c":7
        }]
    }

    This will create only one row combining the results. This feature can be turned off by explicitly passing an argument clubbing = False.

  • The generated table can have some attributes explicitly. E.g. giving an id, class, or any data-* attribute.

  • Python 3 compatible.

Live Demo

Click here for the online demo.

List of Valid Arguments

json2html.convert - The module's convert method accepts the following arguments:

Argument Description
json A valid JSON; This can either be a string in valid JSON format or a Python object that is either dict-like or list-like at the top level.
table_attributes E.g. pass id="info-table" or class="bootstrap-class"/data-* to apply these attributes to the generated table.
clubbing Turn on [default]/off clubbing of list with the same keys of a dict / Array of objects with the same key.
encode Turn on/off [default] encoding of result to escaped HTML, compatible with any browser.
escape Turn on [default]/off escaping of HTML tags in text nodes (prevents XSS attacks in case you pass untrusted data to json2html).

Installation

pip install json2html

Or, Download here and run python setup.py install after changing directory to /json2html

Example Usage

Example 1: Basic usage

from json2html import *
input = {
	"name": "json2html",
	"description": "Converts JSON to HTML tabular representation"
}
json2html.convert(json = input)

Output:

<table border="1"><tr><th>name</th><td>json2html</td></tr><tr><th>description</th><td>converts JSON to HTML tabular representation</td></tr></table>
name description
json2html Converts JSON to HTML tabular representation

Example 2: Setting custom attributes to table

from json2html import *
input = {
	"name": "json2html",
	"description": "Converts JSON to HTML tabular representation"
}
json2html.convert(json = input, table_attributes="id=\"info-table\" class=\"table table-bordered table-hover\"")

Output:

<table id="info-table" class="table table-bordered table-hover"><tr><th>name</th><td>json2html</td></tr><tr><th>description</th><td>Converts JSON to HTML tabular representation</td></tr></table>

Example 3: Clubbing same keys of: Array of Objects

from json2html import *
input = {
	"sample": [{
		"a":1, "b":2, "c":3
	}, {
		"a":5, "b":6, "c":7
	}]
}
json2html.convert(json = input)

Output:

<table border="1"><tr><th>sample</th><td><table border="1"><thead><tr><th>b</th><th>c</th><th>a</th></tr></thead><tbody><tr><td>2</td><td>3</td><td>1</td></tr><tr><td>6</td><td>7</td><td>5</td></tr></tbody></table></td></tr></table>
a c b
1 3 2
5 7 6

Example 4: Each row for different key(s) of: Array of Objects

from json2html import *
input = {
	"sample": [{
		"a":1, "b":2, "c":3
	}, {
		"1a1":5, "1b1":6, "c":7
	}]
}
json2html.convert(json = input)

Output:

<table border="1"><tr><th>sample</th><td><ul><li><table border="1"><tr><th>a</th><td>1</td></tr><tr><th>c</th><td>3</td></tr><tr><th>b</th><td>2</td></tr></table></li><li><table border="1"><tr><th>1b1</th><td>6</td></tr><tr><th>c</th><td>7</td></tr><tr><th>1a1</th><td>5</td></tr></table></li></ul></td></tr></table>

Example 5: [Source: json.org/example <http://json.org/example>_]

from json2html import *

input = {
  "glossary": {
		"title": "example glossary",
		"GlossDiv": {
			"title": "S",
			"GlossList": {
				"GlossEntry": {
					"ID": "SGML",
					"SortAs": "SGML",
					"GlossTerm": "Standard Generalized Markup Language",
					"Acronym": "SGML",
					"Abbrev": "ISO 8879:1986",
					"GlossDef": {
						"para": "A meta-markup language, used to create markup languages such as DocBook.",
						"GlossSeeAlso": ["GML", "XML"]
					},
					"GlossSee": "markup"
				}
			}
		}
	}
}

json2html.convert(json = input)

Output:

<table border="1"><tr><th>glossary</th><td><table border="1"><tr><th>GlossDiv</th><td><table border="1"><tr><th>GlossList</th><td><table border="1"><tr><th>GlossEntry</th><td><table border="1"><tr><th>GlossDef</th><td><table border="1"><tr><th>GlossSeeAlso</th><td><ul><li>GML</li><li>XML</li></ul></td></tr><tr><th>para</th><td>A meta-markup language, used to create markup languages such as DocBook.</td></tr></table></td></tr><tr><th>GlossSee</th><td>markup</td></tr><tr><th>Acronym</th><td>SGML</td></tr><tr><th>GlossTerm</th><td>Standard Generalized Markup Language</td></tr><tr><th>Abbrev</th><td>ISO 8879:1986</td></tr><tr><th>SortAs</th><td>SGML</td></tr><tr><th>ID</th><td>SGML</td></tr></table></td></tr></table></td></tr><tr><th>title</th><td>S</td></tr></table></td></tr><tr><th>title</th><td>example glossary</td></tr></table></td></tr></table>

Tests

cd test/
python run_tests.py

Tested on Python 2.7 and 3.5+.

Contributors

  1. Michel Mueller: @muellermichel

    • Added support for clubbing Array of Objects with same keys, more readable format.
    • Added support for adding custom table_attributes.
    • Convert now accepts unicode and bytestrings for the keyword argument "json".
    • Output now should always appear in the same order as input.
    • Now supports JSON Lists (at top level), including clubbing.
    • Now supports empty inputs and positional arguments for convert.
    • Python 3 support ; Added integration tests for Python 2.6, 3.4 and 3.5 such that support doesn't break.
    • Can now also do the proper encoding for you (disabled by default to not break backwards compatibility).
    • Can now handle non-JSON objects on a best-effort principle.
    • Now by default escapes html in text nodes to prevent XSS attacks.
  2. Daniel Lekic: @lekic

    • Fixed issue with one-item lists not rendering correctly.
    • General code cleanup, fixed all naming conventions and coding standards to adhere to PEP8 conventions.
  3. Kyle Smith: @smithk86

    • Added thead and tbody tags to group header and content rows when creating a table from an array of objects.

Copyright and License

The MIT license <https://opensource.org/licenses/MIT>_

Copyright (c) 2013-2024 Varun Malhotra

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

json2html's People

Contributors

cmutel avatar deepspace2 avatar hugojanruiter avatar hugovk avatar lekic avatar muellermichel avatar nathanbegbie avatar smithk86 avatar softvar 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

json2html's Issues

Html output in Alphabetical order

Hi,
My html output with Alphabetical order instead of my json output file.

Ex: json output is
data [
{
name: 'gopi'
Age: '12'
colour: 'blud'},
{
name: 'john'
Age: ''23'
colour: 'Red'
}
]

my Html output

Age | colour | Name
12 | blue| Gopi
23| red | john

but i need output as
Name| Age| colour

Can someone help me how to sort this ?

Regards
Gopi

column value sample should be removed

from json2html import *
input = {
"sample": [{
"a":1, "b":2, "c":3
}, {
"a":5, "b":6, "c":7
}]
}
json2html.convert(json = input)

above code will have 4 columns whereas it is mentioned in the example that only 3 columns created. please refer example 3.

Dynamically created JSON not supported

The function doesn't provide favorable results on dynamically created json (values collected as json dump from mongodb)
But if the same json is printed in console and the static output is used in code it works exactly as it should.

This doesn't work

response = db.reports.find({"MobileNo":No}) // mongo query returns cursor
aggregate = dumps(response) // dumps json
final['sample'] = aggregate
table = json2html.convert(json = final)

But if you copy the console output of aggregate and pass it a static string to the json2html.convert() it works perfectly
eg print aggregate

[{"eosinophils": "03", "mchc": "336", "hct": "333", "mch": "190", "_id": {"$oid": "567c385ac3ea3256121cb6f5"}, "rbc": "563"}, {"eosinophils": "03", "mchc": "336", "hct": "333", "mch": "190", "_id": {"$oid": "567c3a5ac3ea3256cb1ff2a5"}, "rbc": "563"}]

response = db.reports.find({"MobileNo":No}) // mongo query returns cursor
aggregate = dumps(mongo_query_response)
final['sample'] = [{"eosinophils": "03", "mchc": "336", "hct": "333", "mch": "190", "_id": {"$oid": "567c385ac3ea3256121cb6f5"}, "rbc": "563"}, {"eosinophils": "03", "mchc": "336", "hct": "333", "mch": "190", "_id": {"$oid": "567c3a5ac3ea3256cb1ff2a5"}, "rbc": "563"}]
table = json2html.convert(json = final)

rendering issue

This json is rendered incorrectly in v1.3.0
{ "key10": { "key20": { "a": "a1", "b": "b1", "key30": [1, 2, 3, 4] } } }

The key30 sub-table is displayed before the b/b1 name/value

key10
key20
aa1
key30
  • 1
  • 2
  • 3
  • 4
bb1

Ironically, the online demo works correctly.

Is this 1.0 yet?

Would you say this is "1.0"? It works great. 0.3 will give the impression it isn't functional.

colorful suggest

for Advanced table formatting, Is it a better way to colorful the value?

python 3 support

Hi,

That is a useful module. Thanks.
Do you plan to make it compatible with python3?

Michael

Add support to top to bottom html generation

Sometimes inorder to represent the data properly, we'd want to generate the html top to bottom, i.e., in the fomat. This could be done using the build direction as a custom input.

-------------------------------------
Name  | Age | Gender | DOB |
Rohith | 20    | Male     | Jan  |
-------------------------------------

ImportError: No module named 'jsonconv'

Just did a pip install json2html with no errors. However, when I did "from json2html import *" I got:
from jsonconv import *
ImportError: No module named 'jsonconv'
Where can I get that module to install?
I am running Python 3.4
Perhaps with a little hint I could do the conversion.

Thanks. :)

how to prevent XSS?

thanks for your project.
it's pretty good, I have a question: how to prevent XSS?
does this project provide this function?
thanks :-)

Unicode error prevents installing in python3 using non-UTF locale

Trying to install on a linux system without a configured unicode locale in python3 gives an error:

# pip3 install json2html
Collecting json2html
  Downloading json2html-1.1.1.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-nm_jwbmx/json2html/setup.py", line 17, in <module>
        long_description=open('README.rst').read(),
      File "/usr/lib/python3.5/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 6233: ordinal not in range(128)

A workaround is to actually set an appropriate locale, but this is not always possible or convenient.

Useful element Identification

What are your thoughts on adding identifiers (name/id) to the elements?

Is it useful to set:

  • td or nested table name to the respective key?
  • td class to the respective value type?

Possibly escape apostrophes differently

Hi there,

I'm using your library to produce HTML tables to good effect in most cases.
However, when the dictionary input involves apostrophes, the output fails to play nice with Folium popups.
Using html.escape seems to fix that.
For example, running

from json2html import json2html as jh
import html


d = {'stop_name': "Ponsonby Rd & K'Rd"}
dd = {}
for k, v in d.items():
    try:
        vv = html.escape(v)
    except AttributeError:
        vv = v
    dd[k] = vv

jh.convert(d), jh.convert(dd)

produces

'<table border="1"><tr><th>stop_name</th><td>Ponsonby Rd &amp; K\'Rd</td></tr></table>',
 '<table border="1"><tr><th>stop_name</th><td>Ponsonby Rd &amp;amp; K&amp;#x27;Rd</td></tr></table>'

The first output crashes Folium popups, but the second works with them.
So would it be better for json2html to escape apostrophes in the same way that html.escape does?

Green or Red on HTML template (Only Question)

Hello,

Only Question

It is the best library for json to html ๐Ÿ‘

I have one question:

I use this library for automation test (GUI) with selenium and python.
Is it possible that in the dictionary I have Value = Pass to be colored with Green and when Value = Fail to be colored with Red?

Example json input:

{

"Numar_Special_Achizitie_Mobile_Service_and_Device_6":{

  "Status":"PASSED",

  "HOST Name":"Windows OS",

  "Release":"None Given, Hardcoded",

  "EXECUTION_TS":"20200821124933",

  "Tests Execution Log":{

     "test_page_Login":{

        "Status":"PASSED",

        "ExecutionLog":{

           "Click_OK":"PASSED",

           "Type_UserName":"PASSED",

           "Type_Password":"PASSED",

           "Click_Login":"PASSED",

           "Select by index_DealerSelect":"PASSED"

        }

     },

     "test_page_Search":{

        "Status":"FAIL",

        "ExecutionLog":{

           "Click_MSISDN":"PASSED",

           "Type_searchKey_MSISDN":"PASSED",

           "Click_cauta":"FAIL"

        }

     },

Thanks

Drop support for Python 2.6?

The last Python 2.6 Travis build has failed (which came from #41):

Downloading archive: https://storage.googleapis.com/travis-ci-language-archives/python/binaries/ubuntu/16.04/x86_64/python-2.6.tar.bz2
0.13s$ curl -sSf -o python-2.6.tar.bz2 ${archive_url}
curl: (22) The requested URL returned error: 404 Not Found
Unable to download 2.6 archive. The archive may not exist. Please consider a different version

https://travis-ci.org/softvar/json2html/jobs/583374664

Apparently there are some issues with Ubuntu and Python 2.6 in Travis, Python 2.6 will require the use of dist: trusty (which I believe is itself EOLed).

However, do we still need/want to support Python 2.6? it was EOLed in 2013.

Wrong enum conversion

With the following definition,

class TaskType(str, enum.Enum):
    TASK_TYPE1 = 'task_type1'
    TASK_TYPE2 = 'task_type2'

the enum class instance is converted into a list. I would expect a string instead since str mixin is being inherited.

In [78]: json2html.json2html.convert({'task_type': TaskType.TASK_TYPE1})
'<table border="1"><tr><th>task_type</th><td><ul><li>t</li><li>a</li><li>s</li><li>k</li><li>_</li><li>t</li><li>y</li><li>p</li><li>e</li><li>1</li></ul></td></tr></table>'

Thanks!

from json2html import *

How can I only import "convert". Doing "from json2html import convert" does not work.
I have a situation where "import *" throws error "import * only allowed at module level".

I am not a Python expert, so please understand if there is an obvious solution.

Thanks

JS-Table-Editor to go together with json2html

I've had this idea on how to extend the simplicity of json2html for both read and write operations on the client side.

How about we'd build a JS based on jquery that

(a) runs over a json2html generated table (passing in a jquery selector) and wraps all text nodes except those that have been generated from a json dict key in input text elements. So the whole table becomes a form.

(b) adds a way to add new rows / subtables by allowing to copy a whole json2html generated structure and replace the text content with empty strings. This could be a rightclick-action on the background of the selected structure or some button inserted in a good place.

(c) adds a submit button at the end.

(d) when clicking submit it parses the table and basically does the reverse operation (html2json), so the server can get back a json. The whole implementation should work such that if the user doesn't edit anything, the posted json should be exactly the same as the one that was used to generate the html in the first place.

Now this would be quite a project, but imagine how cool it would be if you could have a configuration editor in your browser for any kind of JSON file and you wouldn't have to lift a finger other than installing json2html on the server and adding this Javascript to the response. It would be trivial to provide that json2html tooling as a Flask plugin as well at that point.

[json2html] Deployment failure- Trying to upgrade the package

Impacted versions:
Master
Steps to reproduce:
When trying to upgrade the package:
Current behavior:
IOError: [Errno 2] No such file or directory: 'README.md'
Expected behavior:
Upgrade the json2html packages sucessfully
Video/Screenshot link (optional):

image

Not a valid JSON list

Hi,
I'v got an issue with json string like:

from json2html import *

aa = [
    {"aaa": 1},
    {"bbb": "ccc"}
]

html = json2html.convert(
    json=aa
)

print html

said:

Exception: Not a valid JSON list

but online demo can handle it w/o problem and it's valid json.

Conda package

Dear developers,

I want to create a Conda package for a package of mine, which has json2html as a dependency.
However, json2html currently does not have a Conda package.

Would it be possible for you to create and publish one?

Thank you very much!
Cheers

Issue for python 2.6.6

I'm not sure if this is just for python 2.6.6, but I ran into an issue when trying to use json2html.

When running a simple script that uses json2html's convert function, I received the following error:

File "/usr/lib/python2.6/site-packages/json2html/jsonconv.py", line 50, in convert
ordered_json = json.loads(self.json_input, object_pairs_hook=ordereddict.OrderedDict)
File "/usr/lib64/python2.6/json/init.py", line 318, in loads
return cls(encoding=encoding, **kw).decode(s)
TypeError: init() got an unexpected keyword argument 'object_pairs_hook'

So there seems to be an issue with the line ordered_json = json.loads(self.json_input, object_pairs_hook=ordereddict.OrderedDict)

I solved this issue on my machine by installing simplejson, and then changing the use of the json library to the simplejson library.

Boolean value

I found this tool quite useful.

Only problem I have is it doesn't convert Boolean value, casting empty.
For example, I tried this json code in JSON Editor Online and it properly shows what I expected.

{
  "Example": {
    "HF": {
        "before": true,
        "after": false
    }
  }
}

However, when I used this tool, it doesn't show any Boolen value.

"border" table attribute is deprecated and not supported in HTML5

Should we consider using style= instead?

The default could be

<style>table, th, td {border: 1px solid black;}</style>
<table><tr><th>name</th><td>Json2Html</td></tr><tr><th>description</th><td>converts json 2 html table format</td></tr></table>

The problem here is that the generated <style> might of course clash with the user's existing style. A longer but safer alternative would be to use inline styles for each <table>, <th> and <td> tag:

<table style="border: 1px solid black;">
    <tr>
        <th style="border: 1px solid black;">name</th>
        <td style="border: 1px solid black;">Json2Html</td>
    </tr>
    <tr>
        <th style="border: 1px solid black;">description</th>
        <td style="border: 1px solid black;">converts json 2 html table format</td>
    </tr>
</table>

UnicodeEncodeError when a key contains non-ascii characters

When a key in the input json contains non-ascii character an UnicodeEncodeError exception is raised.
Proposed change in row 121:

[-] convertedOutput = convertedOutput + '<th>' + str(k) + '</th>'
[+] convertedOutput = convertedOutput + '<th>' + markup(k) + '</th>'

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.