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.

Answer from phihag on Stack Overflow
Top answer
1 of 16
3350

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.

🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Python has a built-in package called json, which can be used to work with JSON data.
Discussions

How to parse JSON file into Python list - Stack Overflow
I am trying to parse a JSON file into Python but failing to print any specific data I am trying to pull from JSON. How can I put these JSON data in separate arrays, so I can play with them in Pyth... More on stackoverflow.com
🌐 stackoverflow.com
How to create a json file from list in python? - Stack Overflow
I am tring to create a json file with my lists in my python code: I have arr_of_id_by_user = [1, 2, 3] arr_of_wallet_amount = [100,3400,200] I would like this to return in the json file like jsonf... More on stackoverflow.com
🌐 stackoverflow.com
How do I read a list of JSON files from file in python? - Stack Overflow
I have a list of JSON files saved to disk that I would like to read. Sometimes the JSON files span more than one line and so, I think that a simple list comprehension that loops over open(file,'rb'). More on stackoverflow.com
🌐 stackoverflow.com
Convert JSON array to Python list - Stack Overflow
There are 2 other ways you can convert it back to a Python list suggested here ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... I’m Jody, the Chief Product and Technology Officer at Stack Overflow. Let’s... ... TypeError when adding a sphere object using the primitive_ico_sphere_add operator and a custom location and scale · Why does this column command keep generating spaces indefinitely when piped to a file... More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-json-to-list
Python Json To List - GeeksforGeeks
July 23, 2025 - In this example, below code uses the `pd.read_json()` method from the pandas library to read a JSON-formatted string into a DataFrame. The subsequent `print` statements display the type of the original string, the list of names extracted from the DataFrame, and the type of the resulting list, respectively. ... import pandas as pd #taking the json file .
Top answer
1 of 4
3

There's just a slight problem with your for loop.

james@VIII:~/Desktop$ ls
f.txt
james@VIII:~/Desktop$ cat f.txt 
{
"Ask":
   {"0":[[9.13,30200],[9.14,106946],[9.15,53072],[9.16,58104],[9.17,45589]],
    "1":[[9.14,106946],[9.15,53072],[9.16,58104],[9.17,45589],[9.18,37521]] },

"Bid":
   {"0":[[9.12,198807],[9.11,1110],[9.1,42110],[9.09,84381],[9.08,98178]],
    "1":[[9.13,13500],[9.12,198807],[9.11,1110],[9.1,42110],[9.09,84381]]}
}
james@VIII:~/Desktop$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> with open('f.txt') as f_in:
...     data = json.load(f_in)
... 
>>> data
{'Ask': {'0': [[9.13, 30200], [9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589]], '1': [[9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589], [9.18, 37521]]}, 'Bid': {'0': [[9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381], [9.08, 98178]], '1': [[9.13, 13500], [9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381]]}}
>>> data['Ask']
{'0': [[9.13, 30200], [9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589]], '1': [[9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589], [9.18, 37521]]}
>>> 
>>> data['Bid']
{'0': [[9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381], [9.08, 98178]], '1': [[9.13, 13500], [9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381]]}
>>> for x in data['Bid']['0']:
...     print(x)
... 
[9.12, 198807]
[9.11, 1110]
[9.1, 42110]
[9.09, 84381]
[9.08, 98178]

Your for loop just needed to be changed a little.

PS you don't need to specify 'r' when reading the file.

You can also get individual values like this:

>>> for x in data['Bid']['0']:
...     print(str(x[0]) + ': ' + str(x[1]))
... 
9.12: 198807
9.11: 1110
9.1: 42110
9.09: 84381
9.08: 98178
2 of 4
0

your for is loop in the keys of dict.

for x in data["Bid"]:
  print(type(x))
# <class 'str'>

try it:

for x in data['Bid']['0']:
 print(x)

or

for x in data['Bid'].values():
 print(x)

sorry for my English :)

🌐
DataCamp
datacamp.com › tutorial › json-data-python
Python JSON Data: A Guide With Examples | DataCamp
December 3, 2024 - Configuration Files. JSON provides a simple and easy-to-read format for storing and retrieving configuration data. This can include settings for the application, such as the layout of a user interface or user preferences. IoT (Internet of Things). IoT devices often generate large amounts of data, which can be stored and transmitted between sensors and other devices more efficiently using JSON. python_obj = { "name": "John Doe", "age": 30, "email": "john.doe@example.com", "is_employee": True, "hobbies": [ "reading", "playing soccer", "traveling" ], "address": { "street": "123 Main Street", "city": "New York", "state": "NY", "zip": "10001" } } print(python_obj)
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - As you learned before, there are Python data types like tuple that you can convert into JSON, but you’ll end up with an array data type in the JSON file. Once you convert the JSON data back to Python, then an array deserializes into the Python list data type.
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to read a json file into a list of dictionaries in python
5 Best Ways to Read a JSON File into a List of Dictionaries in Python - Be on the Right Side of Change
February 22, 2024 - When more control over file reading is required, or when dealing with JSON responses from APIs, the json.loads() function can be used. This function takes a JSON-formatted string as input and returns a Python object.
Find elsewhere
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.4 documentation
February 23, 2026 - Identical to load(), but instead of a file-like object, deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.
🌐
Reddit
reddit.com › r/learnprogramming › how do i make a list of list a json file?
r/learnprogramming on Reddit: How do I make a list of list a JSON file?
April 8, 2022 -

I have a sqlite database were I store my workout exercises. I have been working to get these exercises into a JSON files to send to my website to display graphs using Chartjs.

Going through this article (https://changsin.medium.com/how-to-serialize-a-class-object-to-json-in-python-849697a0cd3) they take two objects and turn them into a JSON output. Like this:

label1 = Label("person", 10, 10, 4, 10)
label2 = Label("car", 20, 20, 5, 11)

image_bboxes = {"image1.jpg": [label1, label2]}

output:
{"version": 1,
"type": "box",
"bounding box":
    {"image1":
        [{"label": "person",
            "x": 10,
            "y": 20
          },
          {"label": "car",
            "x": 10,
            "y": 20
          }
         ]
    }
}

Now I have a list of lists looking like this:

all_exercises = [[planks1, planks2],[bench1,bench2]]

I want to create a JSON output that will allow me to pass it off to my website. Then use JS and Chartjs to display the user selected graph. I can get the graph to do what I want it to do. I don't know how to make the JSON output. I'm not understanding something fundamental when I am using JSON. I just don't know what it is. A book or resource would be greatly appreciated.

My output currently looks like this:

{
  "version": 1,
  "exertest": {
    "second": [
      { //Need's to be labeled PLANK here
        "id": 325,
        "interval": 1,
        "resistance": 0,
        "set_number": 1,
        "workout_id": 58,
        "workout_date": "2022-03-28T06:00",
        "exercise_id": 24,
        "exercise_name": "Plank"
      },
      {
        "id": 326,
        "interval": 1,
        "resistance": 0,
        "set_number": 2,
        "workout_id": 58,
        "workout_date": "2022-03-28T06:00",
        "exercise_id": 24,
        "exercise_name": "Plank"
      },
      {  // Needs to be labeled HIP BRIDGE here
        "id": 327,
        "interval": 15,
        "resistance": 0,
        "set_number": 1,
        "workout_id": 58,
        "workout_date": "2022-03-28T06:00",
        "exercise_id": 25,
        "exercise_name": "Hip Bridge"
      }
    ]
  }
}
Top answer
1 of 2
1
I figured it out. You first have to make sure your list of lists is sorted correctly like this: # find the first exercise of the exercises exercise_id = graph_exercises[0].exercise_id # start a small list big_lst = [] small_lst = [] for i in graph_exercises: # add to small list til exercise changes if i.exercise_id == exercise_id: small_lst.append(i) else: # add small list to big list big_lst.append(small_lst) # start a new small list small_lst = [] exercise_id = i.exercise_id small_lst.append(i) exercises = {"Exercises": big_lst} exercise_col = ExerciseCollection(exercises) json_exercise_col = json.dumps(exercise_col, default=default, indent=1) Then you need a class that will handle the list in a list: ExerciseCollection.py // Create a to_json function and use your list of lists to fill it up //Relative parts of the file are below def to_json(self): to_return = {"version": self.version, "type": self.type} exercises = {} for key, exercises2 in self.exercises2.items(): i_exercises = [] dict_exercise_types = {} for exercise in exercises2: j_exercises = [] k = exercise[0].exercise_name for j in exercise: j_exercises.append(j.__dict__) dict_exercise_types[k] = j_exercises i_exercises.append(dict_exercise_types) exercises[key] = i_exercises to_return["Exercises"] = exercises return to_return That's it. Now on to using the data. Which was not part of my question so will not be answered here.
2 of 2
1
Ah, you want something like data = { "plank": { "field": 123, .... } } Your structure is an array, you want an object instead so you can write data.plank?
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-python-list-to-json
Convert Python List to Json - GeeksforGeeks
July 23, 2025 - JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In Python, the json module provides a convenient way to work with JSON data. In this article, we'll explore how to convert Python lists to JSON, along with some examples.
🌐
Reddit
reddit.com › r/learnpython › convert json list to dictionary
r/learnpython on Reddit: convert JSON list to dictionary
January 13, 2024 -

I must first preface this with the fact that I’m extremely new to python. Like just started learning it a little over a week ago.
I have been racking my brain over how to convert a json object I opened and loaded into a dictionary from a list so I can use the get() function nested within a for loop to do a student ID comparison from another json file (key name in that file is just ID).
Below is the command I’m trying to load the json file:
With open(‘file.json’) as x: object=json.load(x)
When I print(type(object)), it shows up as class list.
Here’s a sample of what the json looks like:
[

{

“Name”: “Steel”,

“StudentID”: 3458274

“Tuition”: 24.99

},

{

“Name”: “Joe”,

“StudentID”: 5927592

“Tuition”: 14.99

}

]
HELP! Thank you!

🌐
Reddit
reddit.com › r/learnpython › list all json keys in a file to identify database column names from a file using python
r/learnpython on Reddit: List all JSON keys in a file to identify database column names from a file using Python
July 9, 2022 -

I am learning Python, and in particular, working with JSON and sqlite in Python. Ultimately I plan to use Python to load the JSON into a sqlite database.

Here is the question: Is there a way in to list all of the keys from a JSON file (not from a string) using Python? I want a list of all of the keys so I can determine what columns I will need/use in my sqlite table(s), without having to manually read the file and make a list.

BTW, this is something along the lines of using INFORMATION_SCHEMA.COLUMNS in SQL Server, or the FINDALL in Python for XML.

All of this is for personal learning, so I'm not looking to use other technologies, I'm sticking to Python, JSON, and sqlite on purpose.

🌐
freeCodeCamp
freecodecamp.org › news › how-to-parse-json-in-python-with-examples
How to Parse JSON in Python – A Complete Guide With Examples
October 29, 2025 - The core functions handle the most common operations: json.loads() parses JSON strings into Python objects, and json.load() reads and parses JSON from files. JSON parsing automatically converts between JSON and Python data types. This conversion lets you work with parsed JSON using standard Python syntax. You can navigate nested JSON by chaining dictionary keys and list indices together.
🌐
Board Infinity
boardinfinity.com › blog › json-file-in-python
JSON file in Python: Read and Write | Board Infinity
January 3, 2025 - To read from a file in Python using JSON the easiest method is using the json.load() method. This function parses the content of a JSON file and transforms it into a Python dictionary (or a list, according to JSON configuration).
🌐
Quora
quora.com › How-do-you-parse-a-JSON-list-in-Python
How to parse a JSON list in Python - Quora
Answer (1 of 3): Before you can start working with JSON in Python, you'll need some JSON to work with. There are a few things that you'll need to set up first. First, create a Python file that will hold your code for these exercises. Inside the file, import the JSON module. [code]import json [/c...
🌐
Reddit
reddit.com › r/learnpython › how to convert nested list into json?
r/learnpython on Reddit: How to convert nested list into JSON?
June 23, 2018 -

I know that, list can be converted into JSON by using json.dumps(mylist).

But how can I convert something like this into JSON ?

[["abc", "bcd", "cde"] , ["pgr", "xyz"]]

🌐
Scaler
scaler.com › home › topics › read, write, parse json file using python
Read, Write, Parse JSON File Using Python - Scaler Topics
April 17, 2024 - Parse the above example file after deserializing it with the json.load( ) function and count the lines to store the students' addresses. Store these values in a list with the person’s name and print the list.