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 Overflow
Top answer
1 of 3
7

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"
      }
    }
  }
}
2 of 3
3

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)
🌐
Reddit
reddit.com › r/learnpython › how would you use python to create json files?
r/learnpython on Reddit: How would you use python to create JSON files?
March 7, 2020 -

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! =^)

Top answer
1 of 4
5
I read two concrete questions from your post: why you would want to create a JSON object Imagine you want multiple software systems to communicate. Let's say we have three systems, one written in Python, one client written in JavaScript and one more backend system in Java. You can't just send Python objects over a network and expect the systems written in JS or Java to understand them. Same thing the other way around. In the end it's just electrical signals and both the sender and receiver need a common understanding of how to interpret those signals, otherwise they will just be gibberish. That's where data formats like JSON come into play: It's a simple and standardized data format that can be handled in any modern programming language. Now your Python code can serialize its internal representation of a piece of data into this format and send it over a network or store it on some disk, where some other system will eventually pick it up, deserialize it into its own internal representation and process it. show how you would create a JSON object with python import json data = {"year": 2020, "sales": 12345678, "currency": "€"} # creating a JSON string json_string = json.dumps(data) # storing it in a file with open("data.json", "w") as json_file: json.dump(data, json_file)
2 of 4
3
If you know about the JSON library, there's not much more to tell. RealPython have excellent tutorials and information. https://realpython.com/python-json/ You can find a lot more by searching "python json tutorial".
Discussions

python 3.x - Most pythonic way to create PDF Files from JSON with Styling? - Stack Overflow
TL;DR: Looking for a python library to create a PDF template with specific styling and fill it with information from JSON file ... I have a long RPA pipeline that ends with 500+ Json documents. Each JSON document represents an exam, each exam might have 1000-4000 Questions. The JSON file is simple, an example ... More on stackoverflow.com
🌐 stackoverflow.com
python - How do I write JSON data to a file? - Stack Overflow
How do I write JSON data stored in the dictionary data to a file? ... For flags when opening file: Here, we used "w" letter in our argument, which indicates write and will create a file if it does not exist in library Plus sign indicates both read and write, guru99.com/reading-and-writing-files-in-python... More on stackoverflow.com
🌐 stackoverflow.com
python - Transform a json file into a pdf - Stack Overflow
I should transform a json file into pdf. I'm having trouble creating a table that allows me to make items that are too long wrap automatically and not overflow to the right side. I paste an example of the json code that I should transform into pdf and then my implementation in python (which ... More on stackoverflow.com
🌐 stackoverflow.com
Markdown to PDF renderer
https://pandoc.org/ Cant't remember the extra thing you need to install for PDF, but it was mentioned in their docs. More on reddit.com
🌐 r/Python
4
5
April 5, 2018
🌐
PyPI
pypi.org › project › pydf2json
pydf2json · PyPI
> pydf.py usage: pydf.py [-h] [-d LOCATION] [-s MAX_SIZE] [-p PASSWORD] [--no_summary] [--show_json] pdf > pydf.py secure_dropbox.pdf -p 29576AE2 Summary of PDF attributes: -------------------------- Encrypted: True User Pass: None Key: 030359FF89FC8A8EB764E97AD2ED7091 Key Length: 128 bits Algo: RC4 Additional Actions: 0 AcroForms: 0 Embedded Files: 0 JS: 0 Launch: 0 Object Streams: 8 OpenActions: 0 Pages: 1 URIs in document: http://<redacted>.xyz/sign-up/ http://<redacted>.xyz/signup/ Document Hashes: SHA1 8733CC6196C7F26F027078E6A51B822462DA2CA3 SHA256 9D64D1EBA74F7078F5F524CCB4F79F3D41F1B7A631DE81D9FF2870FF5E4D2DFD MD5 0F49F102421C286E50CD40EBDDB105AF · pydf.py calls the pydf2json module to convert the PDF into a json-style dict and then accesses the structure to create the summary you see above.
🌐
Flinks
help.flinks.com › support › solutions › articles › 43000729546-how-to-convert-the-a-json-payload-to-a-pdf-file-python-
How to convert the a .json payload to a .pdf file (python) :
June 6, 2024 - import json from fpdf import FPDF ... a pretty printed string json_str = json.dumps(data, indent=4) # Create a PDF instance pdf = FPDF() pdf.set_auto_page_break(auto=True, margin=15) pdf.add_page() pdf.set_font("Arial", size=12) ...
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
If you have a Python object, you can convert it into a JSON string by using the json.dumps() method.
Top answer
1 of 16
3357

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.

2 of 16
347

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.

Find elsewhere
🌐
PyPI
pypi.org › project › json2pdf-Converter
json2pdf-Converter · PyPI
September 1, 2023 - # json2pdf_converter `json2pdf_converter` is a Python package that simplifies the process of converting JSON data into PDF files using a specified HTML template. This is particularly useful for creating dynamic PDF reports or documents from ...
Top answer
1 of 2
2

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

2 of 2
0

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:

🌐
Aspose
products.aspose.com › aspose.cells › python via java › conversion › json to pdf
Python JSON to PDF - JSON to PDF Converter | products.aspose.com
July 1, 2026 - Add a library reference (import the library) to your Python project. Load JSON file with an instance of Workbook. Convert JSON to PDF by calling Workbook.save method.
🌐
Programiz
programiz.com › python-programming › json
Python JSON: Read, Write, Parse JSON (With Examples)
To work with JSON (string, or file containing JSON object), you can use Python's json module.
🌐
YouTube
youtube.com › watch
How to Create a JSON file in Python (Python and JSON Tutorial 03) - YouTube
In this video, we work with the same data as before and we explore how to create a json file. This is an easy tutorial.If you enjoy this video, please subscr...
Published: April 7, 2020
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
July 21, 2026 - In other words, you can create JSON files using the code editor of your choice. Once you set the file extension to .json, most code editors display your JSON data with syntax highlighting out of the box: The screenshot above shows how VS Code displays JSON data using the Bearded color theme. You’ll have a closer look at the syntax of the JSON format next! ... In the previous section, you got a first impression of how JSON data looks. And as a Python developer, the JSON structure probably reminds you of common Python data structures, like a dictionary that contains a string as a key and a value.
🌐
GeeksforGeeks
geeksforgeeks.org › python › build-a-json-object-in-python
Build a Json Object in Python - GeeksforGeeks
July 23, 2025 - In this example, the json.loads() function is used to parse a JSON-formatted string json_string into a Python dictionary named data. The resulting dictionary is then printed, representing the decoded JSON data.
🌐
Srinimf
srinimf.com › 2021 › 11 › 12 › how-to-create-json-file-in-python
How to Create a JSON File in Python: Step-by-Step Guide for Beginners – Srinimf
October 12, 2025 - Opening the File with open('data.json', 'w', encoding='utf-8') as f: ... Do import JSON, which is the first step that pulls the JSON package into the program. So we can use all the available JSON methods.
🌐
CCMC
ccmc.gsfc.nasa.gov › scoreboards › sep › writing-sepsb-json-guide
How to write your data to a JSON file | NASA CCMC
Download and use the CCMC-created JSON helper script · The best way to write your data to a JSON file is to load the JSON library for your language and use it to write out a JSON file. This is the best method to ensure that the JSON is properly formatted. Here is an example from https://stackabuse.com/reading-and-writing-json-to-a-file-in-python...
🌐
Pdfs
pdfs.build › home › blog › how to generate pdfs from json data with an api
How to Generate PDFs from JSON Data with an API | pdfs.build
April 9, 2026 - Libraries like pdfkit (Node), fpdf ... 90).stroke(); // ...hundreds of lines for a real invoice · Define a template with variables, pass data as JSON, get a PDF back....
🌐
CodeSignal
codesignal.com › learn › courses › hierarchical-and-structured-data-formats › lessons › constructing-objects-and-writing-to-json-files
Constructing Objects and Writing to JSON Files
Ensure data types in Python are compatible with JSON (e.g., dictionaries and lists). Always close files to avoid resource leaks; the with statement is a helpful tool here. Use indent to create human-readable JSON files—this can be useful for debugging and manual inspection. Note that indent=4 uses 4 spaces, and you can adjust the number according to your formatting preference. However, if you need your JSON file to be compact (for example, if you need to transfer it or store a large amount of data), it is useful to omit indentation.
🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-and-writing-json-to-a-file-in-python
Reading and Writing JSON to a File in Python - GeeksforGeeks
It takes two parameters: dictionary: ... simply write it to a file using the "write" function. Example: Convert a dictionary to a JSON string and write it to a file....
Published: August 5, 2025
🌐
SysTools Group
systoolsgroup.com › home › how to › how to convert json to pdf in 2026? 3 expert ways
Top Methods to Convert JSON to PDF (Free, Python & Converter)
January 2, 2026 - For developers, using a programming ... to transform JSON data into a professional-looking PDF. Follow the steps given below: Write JSON Data. Create a PDF class....