🌐
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.
🌐
LearnPython.com
learnpython.com › blog › json-in-python
How to Convert a String to JSON in Python | LearnPython.com
The dumps() method converts a Python object to a JSON formatted string. We can also create a JSON file from data stored in a Python dictionary.
Discussions

python - How do I write JSON data to a file? - Stack Overflow
Because the json string that I produced is coming from dataframe.to_json(). 2023-07-31T03:11:11.25Z+00:00 ... Might be worth to point out that ensure_ascii=False is not the default and needed for words like grün. 2026-02-03T19:20:22.357Z+00:00 ... Save this answer. ... Show activity on this post. To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python ... More on stackoverflow.com
🌐 stackoverflow.com
python - How to save a string to a json file - Stack Overflow
I want to save a string to a json file, but when I do it will write it with \" and with quotes at the beginning and at the end. import json name_c = ['Don', 'Perez'] my_details = "data = {" + "... More on stackoverflow.com
🌐 stackoverflow.com
How would you use python to create JSON files?
From StackOverflow JSON is basically a way of communicating data to someone, with very specific rules. Using Key Value Pairs and Arrays. JSON is very lightweight and is a nice way to store information. If you request a web-server, most responses will be in JSON format. Example of JSON data (also from StackOverflow): { "first_name": "John", "last_name": "Smith", "address": { "street_address": "21 2nd Street", "city": "New York", "state": "NY", "postal_code": 10021 }, "phone_numbers": [ "212 555-1234", "646 555-4567" ] } Now, to answer your question. How to create JSON files using Python? First, you need valid JSON in your Python code. images = [ { "name": "awesome_image.png", "file_size": 1240000, "file_type": "image/png", }, { "name": "good_image.jpg", "file_size": 742600, "file_type": "image/jpeg" } ] Now, using the json library # Load data. This will transform the data into an indented string. json_data = json.dumps(images, indent=2) # Create and write to file. with open("/home/user/Documents/images.json", "w") as json_file: json_file.write(json_data) How to load JSON files in Python? # Open file in read mode. with open("/home/user/Documents/images.json", "r") as f: # We can do this in two ways. # 1. Load file directly. data = json.load(f) # 2. Load from the file's contents. data = json.loads(f.read()) Now all the file content is stored in the data variable. If you are dealing with files, it's better to load and work with them in Python. It'll be faster than to keep opening and closing files all the time. Create functions to write/load files and use them when you need to. More on reddit.com
🌐 r/learnpython
7
5
March 7, 2020
How To Combine Two Json Values
That will create a new file containing an array of the first 5 elements of the input array. ... You would be much better off doing this in Python, which has JSON reader libraries readily available. It would also be much faster than a Bash effort to do this. ... I might finally learn what goes on in JSON files! ... Representing very long strings... More on reddit.com
🌐 r/bash
14
12
August 19, 2019
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
July 21, 2026 - You can write JSON with Python by using the json.dump() function to serialize Python objects into a JSON file. ... You connect JSON with Python by using the json module to serialize Python objects into JSON and deserialize JSON data into Python ...
🌐
Vertabelo Academy
academy.vertabelo.com › course › python-json › writing-json-files › writing-to-json-file › convert-a-string-into-a-json-file
How to Read and Write JSON Files in Python | Learn Python | Vertabelo Academy
No problem – we simply use the json.dump() function. (Note: That's dump without an "s".) This function writes the data converted to its JSON representation into a file. Have a look: with open('data.json', 'w') as outfile: json.dump(data, outfile) ...
🌐
Python Examples
pythonexamples.org › python-create-json
Python Create JSON
In Python, you can create JSON string by simply assigning a valid JSON string literal to a variable, or convert a Python Object to JSON string using json.loads() function. In this tutorial, we will create JSON from different types of Python objects.
🌐
freeCodeCamp
freecodecamp.org › news › python-json-how-to-convert-a-string-to-json
Python JSON – How to Convert a String to JSON
November 9, 2021 - // It defines the first name and last name of an employee · To use JSON with Python, you'll first need to include the JSON module at the top of your Python file. This comes built-in to Python and is part of the standard library.
🌐
Python Examples
pythonexamples.org › python-write-json-to-file
Python Write JSON to File
To write JSON to File in Python, first prepare the JSON string using json.dumps() method, and then create a JSON file and write the prepared JSON string to the file using open() and file.write() functions.
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.

🌐
Programiz
programiz.com › python-programming › json
Python JSON: Read, Write, Parse JSON (With Examples)
To write JSON to a file in Python, we can use json.dump() method. import json person_dict = {"name": "Bob", "languages": ["English", "French"], "married": True, "age": 32 } with open('person.txt', 'w') as json_file: json.dump(person_dict, json_file) In the above program, we have opened a file ...
Find elsewhere
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.7 documentation
If zero, negative, or "" (the empty string), only newlines are inserted. If None (the default), no newlines are inserted. separators (tuple | None) – A two-tuple: (item_separator, key_separator). If None (the default), separators defaults to (', ', ': ') if indent is None, and (',', ': ') otherwise. For the most compact JSON, specify (',', ':') to eliminate whitespace.
🌐
GeeksforGeeks
geeksforgeeks.org › python › reading-and-writing-json-to-a-file-in-python
Reading and Writing JSON to a File in Python - GeeksforGeeks
Explanation: We define a JSON string and use json.loads() to parse it into a Python dictionary, then print the resulting object and its type. Writing data to a JSON file in Python involves converting Python objects like dictionaries into JSON ...
Published: August 5, 2025
🌐
GeeksforGeeks
geeksforgeeks.org › python › build-a-json-object-in-python
Build a Json Object in Python - GeeksforGeeks
July 23, 2025 - import json def encoder(obj): if isinstance(obj, set): return list(obj) return obj gfg = [('name', 'Hustlers'), ('age', 19), ('is_student', True)] json_data = dict(gfg) json_string = json.dumps(json_data, default=encoder) print(type(json_string)) print(json_string)...
🌐
Stack Abuse
stackabuse.com › reading-and-writing-json-to-a-file-in-python
Reading and Writing JSON to a File in Python
April 18, 2023 - If you encounter this edge-case, which has since been fixed in subsequent Python versions - try using json.dumps() instead, and write the string contents into a file instead of streaming the contents directly into a file.
🌐
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.
🌐
Board Infinity
boardinfinity.com › blog › json-file-in-python
JSON file in Python: Read and Write | Board Infinity
January 3, 2025 - Indentation: Estimate the indent of the JSON string which will make the JSON string more easily understandable and readable. Indents = 4 nests the data structures making them have additional spacing. Sorting Keys: You can also use the sort_keys=True parameter for the keys to be sorted in alphabetical order. #format and write json file in python json.dump(data, file, indent=4, sort_keys=True)
🌐
DataCamp
datacamp.com › tutorial › json-data-python
Python JSON Data: A Guide With Examples | DataCamp
December 3, 2024 - Here are some common functions from json library that are used for serialization and deserialization. This function is used to serialize a Python object into a JSON string. The dumps() function takes a single argument, the Python object, and returns a JSON string.
🌐
Delft Stack
delftstack.com › home › howto › python › write json to file in python
How to Write JSON to a File in Python | Delft Stack
February 2, 2024 - Then we are creating and opening a new file with the name that we chose in the write mode. Then, we use the loads function from the json module to convert the JSON string to a python dictionary to write it to a file.
🌐
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".
🌐
Code Institute
codeinstitute.net › blog › python › working with json in python: a beginner’s guide
Working with JSON in Python: A Beginner's Guide - Code Institute Global
February 6, 2024 - It illustrates how Python can be integrated with command-line tools like `json.tool` to perform specific tasks directly from the command line. While the `json` module can handle basic Python types (e.g., dictionaries, lists, strings, numbers), it may encounter difficulties when trying to encode custom objects.