Just use normal dictionaries in python when constructing the JSON then use the JSON package to export to JSON files.
You can construct them like this (long way):
a_dict = {}
a_dict['id'] = {}
a_dict['id']['a'] = {'properties' : {}}
a_dict['id']['a']['properties']['x'] = '9'
a_dict['id']['a']['properties']['y'] = '3'
a_dict['id']['a']['properties']['z'] = '17'
a_dict['id']['b'] = {'properties' : {}}
a_dict['id']['b']['properties']['x'] = '3'
a_dict['id']['b']['properties']['y'] = '2'
a_dict['id']['b']['properties']['z'] = '1'
or you can use a function:
def dict_construct(id, x, y, z):
new_dic = {id : {'properties': {} } }
values = [{'x': x}, {'y': y}, {'z':z}]
for val in values:
new_dic[id]['properties'].update(val)
return new_dic
return_values = [('a', '9', '3', '17'), ('b', '3', '2', '1')]
a_dict = {'id': {} }
for xx in return_values:
add_dict = dict_construct(*xx)
a_dict['id'].update(add_dict)
print(a_dict)
both give you as a dictionary:
{'id': {'a': {'properties': {'x': '9', 'y': '3', 'z': '17'}}, 'b': {'properties': {'x': '3', 'y': '2', 'z': '1'}}}}
using json.dump:
with open('data.json', 'w') as outfile:
json.dump(a_dict, outfile)
you get as a file:
{
"id": {
"a": {
"properties": {
"x": "9",
"y": "3",
"z": "17"
}
},
"b": {
"properties": {
"x": "3",
"y": "2",
"z": "1"
}
}
}
}
Answer from Anna Nevison on Stack OverflowJust use normal dictionaries in python when constructing the JSON then use the JSON package to export to JSON files.
You can construct them like this (long way):
a_dict = {}
a_dict['id'] = {}
a_dict['id']['a'] = {'properties' : {}}
a_dict['id']['a']['properties']['x'] = '9'
a_dict['id']['a']['properties']['y'] = '3'
a_dict['id']['a']['properties']['z'] = '17'
a_dict['id']['b'] = {'properties' : {}}
a_dict['id']['b']['properties']['x'] = '3'
a_dict['id']['b']['properties']['y'] = '2'
a_dict['id']['b']['properties']['z'] = '1'
or you can use a function:
def dict_construct(id, x, y, z):
new_dic = {id : {'properties': {} } }
values = [{'x': x}, {'y': y}, {'z':z}]
for val in values:
new_dic[id]['properties'].update(val)
return new_dic
return_values = [('a', '9', '3', '17'), ('b', '3', '2', '1')]
a_dict = {'id': {} }
for xx in return_values:
add_dict = dict_construct(*xx)
a_dict['id'].update(add_dict)
print(a_dict)
both give you as a dictionary:
{'id': {'a': {'properties': {'x': '9', 'y': '3', 'z': '17'}}, 'b': {'properties': {'x': '3', 'y': '2', 'z': '1'}}}}
using json.dump:
with open('data.json', 'w') as outfile:
json.dump(a_dict, outfile)
you get as a file:
{
"id": {
"a": {
"properties": {
"x": "9",
"y": "3",
"z": "17"
}
},
"b": {
"properties": {
"x": "3",
"y": "2",
"z": "1"
}
}
}
}
One way will be to create whole dict at once:
data = {}
for i in range(1, 5):
name = getname(i)
x = getx(i)
y = gety(i)
z = getz(i)
data[name] = {
"x": x,
"y": y,
"z": z
}
And then save
with open('data.json', 'w') as f:
json.dump(data, f, indent=4)
Howdy!
I recently took a coding test for an internship program, I was quickly put in check by the coding test. I am only about 50 hours into coding, but I had higher hopes for myself then how I performed.
The questions that tripped me up were how to take input in the form of a Dict [] and create a JSON object out of it. I was allowed to read documentation during the test and found the JSON library with json.dumps, but couldn't figure out how to use it in the allotted time. =^(
In the spirit of improvement would you fine folks of r/learnpython be willing to show how you would create a JSON object with python, and outline some reasons as to why you would want to create a JSON object in the first place? I'm hoping to learn something new, but I also hope that there are a few on this sub who can come across the post and learn something new too.
On the bright side, I solved FizzBuzz no problem. That problem gave me anxiety when I first started coding, and now I can solve it expertly. Little wins!
Thank you! =^)
python 3.x - Most pythonic way to create PDF Files from JSON with Styling? - Stack Overflow
python - How do I write JSON data to a file? - Stack Overflow
python - Transform a json file into a pdf - Stack Overflow
Markdown to PDF renderer
data is a Python dictionary. It needs to be encoded as JSON before writing.
Use this for maximum compatibility (Python 2 and 3):
import json
with open('data.json', 'w') as f:
json.dump(data, f)
On a modern system (i.e. Python 3 and UTF-8 support), you can write a nicer file using:
import json
with open('data.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
See json documentation.
To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:
import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False))
The code is simpler in Python 3:
import json
with open('data.txt', 'w') as f:
json.dump(data, f, ensure_ascii=False)
On Windows, the encoding='utf-8' argument to open is still necessary.
To avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:
import json, codecs
with open('data.txt', 'wb') as f:
json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)
The codecs.getwriter call is redundant in Python 3 but required for Python 2
Readability and size:
The use of ensure_ascii=False gives better readability and smaller size:
>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'
>>> len(json.dumps({'абвгд': 1}))
37
>>> len(json.dumps({'абвгд': 1}, ensure_ascii=False).encode('utf8'))
17
Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.
There seems to be a lot of steps in your code. You could simply loop over the columns of your transposed df and export each of them to html. Append all html tables to a root html element and export with pdfkit:
import json
import pandas as pd
import lxml.etree as et
import pdfkit
your_json = """{"url": "https://www.abc123.com", "extensionVersion": "4.51.0", "axeVersion": "4.6.3", "standard": "WCAG 2.1 AA", "testingStartDate": "2023-04-03T09:35:06.177Z", "testingEndDate": "2023-04-03T09:35:06.177Z", "bestPracticesEnabled": false, "issueSummary": {"critical": 2, "moderate": 0, "minor": 0, "serious": 0, "bestPractices": 0, "needsReview": 0}, "remainingTestingSummary": {"run": false}, "igtSummary": [], "failedRules": [{"name": "button-name", "count": 1, "mode": "automated"}, {"name": "select-name", "count": 1, "mode": "automated"}], "needsReview": [], "allIssues": [{"ruleId": "button-name", "description": "Ensures buttons have discernible text", "help": "Buttons must have discernible text", "helpUrl": "https://www.abc123.com", "impact": "critical", "needsReview": false, "isManual": false, "selector": [".livechat-button"], "summary": "Fix any of the following:\\n Element does not have inner text that is visible to screen readers\\n aria-label attribute does not exist or is empty\\n aria-labelledby attribute does not exist, references elements that do not exist or references elements that are empty\\n Element has no title attribute\\n Element's default semantics were not overridden with role=\\"none\\" or role=\\"presentation\\"", "source": "<button class=\\"livechat-button items-center bg-black shadow-liveChat rounded-full text-white p-2 h-12 transition-all opacity-0 pointer-events-none w-sp-48 opacity-0 pointer-events-none\\">", "tags": ["cat.name-role-value", "wcag2a", "wcag412", "section508", "section508.22.a", "ACT"], "igt": "", "shareURL": "", "createdAt": "2023-04-03T09:35:06.177Z", "testUrl": "", "testPageTitle": "ABC123", "foundBy": "ab@bc.com", "axeVersion": "4.6.3"}, {"ruleId": "select-name", "description": "Ensures select element has an accessible name", "help": "Select element must have an accessible name", "helpUrl": "https://www.abc123.com", "impact": "critical", "needsReview": false, "isManual": false, "selector": ["#plp__sortSelected"], "summary": "Fix any of the following:\\n Form element does not have an implicit (wrapped) <label>\\n Form element does not have an explicit <label>\\n aria-label attribute does not exist or is empty\\n aria-labelledby attribute does not exist, references elements that do not exist or references elements that are empty\\n Element has no title attribute\\n Element's default semantics were not overridden with role=\\"none\\" or role=\\"presentation\\"", "source": "<select class=\\"w-full absolute opacity-0 appearance-none text-value-small font-bold text-black uppercase cursor-pointer bg-transparent outline-0\\" id=\\"plp__sortSelected\\">", "tags": ["cat.forms", "wcag2a", "wcag412", "section508", "section508.22.n", "ACT"], "igt": "", "shareURL": "", "createdAt": "2023-04-03T09:35:06.177Z", "testUrl": "https://www.abc123.com", "testPageTitle": "ABC123", "foundBy": "ab@bc.com", "axeVersion": "4.6.3"}]}"""
data = json.loads(your_json)
## replace the above lines with the following in your case
# with open('your_file.json', 'r') as f:
# data = json.load(f)
html = et.Element("html")
# general info
html.append(et.fromstring(f"""<h3>Site link: <a href="{data['url']}">{data['url']}</a></h3>"""))
html.append(et.fromstring(f"""<h4>Date: {data['testingEndDate']}</h4>"""))
html.append(et.fromstring(f"""<h4>Summary:</h4>"""))
# summary table
summary = pd.Series(data['issueSummary'])
summary_table = et.fromstring(summary.to_frame().to_html(header=False))
summary_table.set('class', 'summary')
html.append(summary_table)
# issue tables
cols_of_interest = ['ruleId', 'description', 'help', 'impact', 'selector', 'summary', 'source']
df = pd.DataFrame(data['allIssues'])[cols_of_interest].T
for col in df.columns:
table = et.fromstring(df[[col]].to_html(header=False))
table.set('class', 'issue')
html.append(table)
html.append(et.fromstring('<br/>'))
pdfkit.from_string(et.tostring(html, encoding="unicode"), "./output.pdf", css='style.css')
With the following css file:
/* style.css */
* {
font-family: 'Liberation Sans';
}
table {
margin: 20px;
margin-left: auto;
margin-right: auto;
}
table.summary {
width: 50%;
}
table.issue{
border: 0;
width: 100%;
border-collapse: collapse;
}
table.issue td,
table.issue th {
border: 0;
text-align: left;
padding: 5px;
}
table.issue tr {
border-bottom: 1px solid #dddddd;
}
You'll get:

Edit: updated json with the data you provided + exporting additional data + improved css
Note: you will need to install wkhtmltopdf and make sure that it is in your path.
Edit2: limiting output to desired fields
disclaimer: I am the author of borb, the library used in this answer.
Assuming your data looks like this:
data = [
{
"ruleId":"name",
"description":"Description123",
"help":"Description234",
"impact":"critical",
"selector":[
"abc1234"
],
"summary":"long text",
"source":"long text2",
},
]
You can run the following code:
from borb.pdf import Document, Page, PageLayout, SingleColumnLayout, Paragraph, HexColor, Table, TableUtil
from decimal import Decimal
# create empty document
doc: Document = Document()
# create empty page
page: Page = Page()
doc.add_page(page)
# use a PageLayout to be able to add things easily
layout: PageLayout = SingleColumnLayout(page)
# generate a Table for each issue
for i, issue in enumerate(data):
# add a header (Paragraph)
layout.add(Paragraph("Issue %d" % i, font_size=Decimal(20), font_color=HexColor("#B5F8FE")))
# add a Table (using the convenient TableUtil class)
table: Table = TableUtil.from_2d_array([["Rule ID", issue.get("ruleId", "N.A.")],
["Description", issue.get("description", "N.A.")],
["Help", issue.get("help", "N.A.")],
["Impact", issue.get("impact", "N.A.")],
["Selector", str(issue.get("selector", []))],
["Summary", issue.get("summary", "N.A.")],
["Source", issue.get("source", "N.A.")],
], header_row=False, header_col=True, flexible_column_width=False)
layout.add(table)
# store the PDF
with open("output.pdf", "wb") as fh:
PDF.dumps(fh, doc)
This generates the following PDF:
