You can use a list comprehension to produce a list of dictionaries, then convert that:

json_string = json.dumps([ob.__dict__ for ob in list_name])

or use a default function; json.dumps() will call it for anything it cannot serialise:

def obj_dict(obj):
    return obj.__dict__

json_string = json.dumps(list_name, default=obj_dict)

The latter works for objects inserted at any level of the structure, not just in lists.

Personally, I'd use a project like marshmallow to handle anything more complex; e.g. handling your example data could be done with

from marshmallow import Schema, fields

class ObjectSchema(Schema):
    city = fields.Str()
    name = fields.Str()

object_schema = ObjectSchema()
json_string = object_schema.dumps(list_name, many=True)
Answer from Martijn Pieters on Stack Overflow
🌐
Python Examples
pythonexamples.org › python-json-to-list
Python JSON to List
After loading the JSON string to list, we shall print the value for key "b". import json jsonStr = '[{"a":1, "b":2}, {"c":3, "d":4}]' aList = json.loads(jsonStr) print(aList[0]['b']) ... In this example, we will take a JSON String with Array of Arrays and convert it to Python List of Lists.
Discussions

Convert JSON array to Python list - Stack Overflow
That is my JSON array, but I would want to convert all the values in the 'fruits' string to a Python list. What would be the correct way of doing this? ... You have a JSON Object containing an Array. A JSON Array is homologous to a Python list. A JSON Object is homologous to a Python dict. More on stackoverflow.com
🌐 stackoverflow.com
Python Convert JSON Array to Corresponding List of Python Objects - Stack Overflow
Couldn't find an already existing post that addressed how to do this: I have a JSON Array, like [{'completed': 0, 'content': 'do smtng', 'deadline': 'Mon, 22 Nov 2021 00:00:00 GMT', 'id': 4, 'user_... More on stackoverflow.com
🌐 stackoverflow.com
Elegant way to convert json to list of objects in Python 3 - Stack Overflow
Is there a more elegant way to parse a json file containing an array of elements? Example: import json contents = ... # read json file # 'elements_dict' is an array of dictionaries elements_dict ... More on stackoverflow.com
🌐 stackoverflow.com
convert list of dictionary to list of json objects
Json.dumps will convert the dictionary to a string but the string is valid JSON. You see the single quotes since Python is indicating this is a string (and double quotes is being used internally). More on reddit.com
🌐 r/learnpython
7
2
October 13, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-json-to-list
Python Json To List - GeeksforGeeks
July 23, 2025 - In this example, the below code utilizes the `json.loads()` method to convert a JSON-formatted string `[1,2,3,4]` into a Python list named `array`. The `print` statements display the type of the original string, the first element of the resulting ...
Top answer
1 of 2
5

What you are looking to do is deserialize a json object to a class, I'm sure there are better answers than this one but here goes.

First Step: convert json array to python list

import json
# assuming it is a json object for now, you can loop through an do the same
json = {'completed': 0, 'content': 'do smtng', 'deadline': 'Mon, 22 Nov 2021 00:00:00 GMT', 'id': 4, 'user_id': 7}
job = json.loads(json)

Second Step: Converting our list to a class

There's not really a consensus here on how to do this. You can try libraries like attrs if your json is already formatted with the exact naming of your class, or you can do something manual like this:

import json
from dataclasses import dataclass


@dataclass
class Task:
    completed: int
    content: str
    deadline: str
    id: int
    user_id: int
    
    @classmethod
    def from_dict(cls, dict):
        return cls(completed=dict["completed"], content=dict["content"],
                   deadline=dict["deadline"], id=dict["id"],
                   user_id=dict["user_id"])

    @classmethod
    def from_json(cls, json_str: str):
        return cls.from_dict(json.loads(json_str))

You can perform input validation here too if you want but trying to keep it basic

2 of 2
2

If you're ok with using external libraries, the simplest solution would be to use the builtin dataclasses module in Python 3.7+ along with the dataclass-wizard library for (de)serialization purposes.

Here's a simple enough example using data classes to model your data in this case. Note that I'm using a new feature, patterned date and time, to de-serialize a custom pattern string to a datetime object. If you want to keep the data as a string, you can annotate it just like deadline: str instead. I was able to use the format codes from the docs on datetime.

import json
from dataclasses import dataclass

from dataclass_wizard import fromlist, asdict, DateTimePattern


@dataclass
class Task:
    completed: int
    content: str
    deadline: DateTimePattern['%a, %d %b %Y %H:%M:%S %Z']
    id: int
    user_id: int


list_of_dict = [
    {'completed': 0, 'content': 'do smtng', 'deadline': 'Mon, 22 Nov 2021 00:00:00 GMT', 'id': 4, 'user_id': 7},
]

# De-serialize JSON data into a list of Task instances
list_of_tasks = fromlist(Task, list_of_dict)
print(list_of_tasks)

# Serialize list of Task instances
json_string = json.dumps([asdict(task) for task in list_of_tasks])
print(json_string)

Output:

[Task(completed=0, content='do smtng', deadline=datetime.datetime(2021, 11, 22, 0, 0), id=4, user_id=7)]
[{"completed": 0, "content": "do smtng", "deadline": "2021-11-22T00:00:00", "id": 4, "userId": 7}]

To make things a bit simpler, you can opt to subclass from the JSONWizard Mixin class. The main benefit here is a bunch of added helper class methods, like list_to_json which will serialize a list of dataclass instances to JSON, which seems like it could be useful in this case. This example is similar to the one above; note the output is the same in any case.

from dataclasses import dataclass

from dataclass_wizard import JSONWizard, DateTimePattern


@dataclass
class Task(JSONWizard):
    completed: int
    content: str
    deadline: DateTimePattern['%a, %d %b %Y %H:%M:%S %Z']
    id: int
    user_id: int


list_of_dict = [
    {'completed': 0, 'content': 'do smtng', 'deadline': 'Mon, 22 Nov 2021 00:00:00 GMT', 'id': 4, 'user_id': 7},
]

# De-serialize JSON data into a list of Task instances
list_of_tasks = Task.from_list(list_of_dict)
print(list_of_tasks)

# Serialize list of Task instances
json_string = Task.list_to_json(list_of_tasks)
print(json_string)
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - A key-value pair in a JSON object is separated by a colon (:). On the left side of the colon, you define a key. A key is a string you must wrap in double quotes ("). Unlike Python, JSON strings don’t support single quotes ('). The values in a JSON document are limited to the following data types: Just like in dictionaries and lists, you’re able to nest data in JSON objects and arrays.
Find elsewhere
🌐
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. ... In this example, a Python list containing a mix of integers and strings (list_1) is converted to a JSON-formatted string (json_str) using json.dumps().
🌐
DataCamp
datacamp.com › tutorial › json-data-python
Python JSON Data: A Guide With Examples | DataCamp
December 3, 2024 - While Python is capable of storing intricate data structures such as sets and dictionaries, JSON is limited to handling strings, numbers, booleans, arrays, and objects. Let’s look at some of the differences: To convert a Python list to JSON format, you can use the json.dumps() method from ...
🌐
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...
🌐
Quora
quora.com › How-do-I-convert-a-list-to-JSON-in-Python
How to convert a list to JSON in Python - Quora
There is a inbuilt package which python provides called json. Simply import it then make a simple list and then write json.dumps(list). I think it will do the job. Another way to do : but its beneficial for large no.
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
The json.dumps() method has parameters to make it easier to read the result: Use the indent parameter to define the numbers of indents: ... You can also define the separators, default value is (", ", ": "), which means using a comma and a space ...
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › convert python list to json examples
Convert Python List to JSON Examples - Spark By {Examples}
March 27, 2024 - For example, the list my_list_of_dicts contains dictionaries as its elements. The json.dumps() function is then used to convert this list to a JSON-formatted string. The indent=2 parameter is optional and adds indentation for better readability.
🌐
EyeHunts
tutorial.eyehunts.com › home › python list of objects to json | example code
Python list of objects to JSON | Example code
November 30, 2022 - You can use a list comprehension to produce a list of dictionaries, then convert that using json.dumps() function. A simple example codes a dump method in your object and uses it when sending things to json module:
🌐
TestMu AI Community
community.testmuai.com › ask a question
How can I convert a JSON array to a Python list? - TestMu AI Community
November 26, 2024 - I have the following JSON array: import json array = '{"fruits": ["apple", "banana", "orange"]}' data = json.loads(array) In this case, I want to convert all the values in the ‘fruits’ string to a Python list. What is…
🌐
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.

🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.3 documentation
1 month ago - The old version of JSON specified by the obsolete RFC 4627 required that the top-level value of a JSON text must be either a JSON object or array (Python dict or list), and could not be a JSON null, boolean, number, or string value.
Top answer
1 of 3
2

make it this way:

def getTasks(filename):
    f = open(filename, 'r')
    a = open('tasksJSON', 'w')
    x = []
    d = xmltodict.parse(f)
    l = d.get('Project').get('Tasks').get('Task')
    for task in l:
        if (task['Name'] == 'dinner'):  #criteria for desirable tasks
            #j = json.dumps(task)
            x.append(task)
            #a.write (str(j))   
            #a.write(',')         

    a.write(json.dumps(x))
    f.close()
    a.close()
2 of 3
1

JSON doesn't allow extra commas at the end of an array or object. But your code adds such an extra comma. If you look at the official grammar here, you can only have a , before another value. And Python's json library conforms to that grammar, so:

>>> json.loads('[1, 2, 3, ]')
ValueError: Expecting value: line 1 column 8 (char 7)

To fix this, you could do something like this:

first = True
for task in l:
    if (task['Name'] == 'dinner'):  #criteria for desirable tasks
        if first:
            first = False
        else:
            a.write(',')
        j = json.dumps(task)
        a.write(str(j))   

On the other hand, if memory isn't an issue, it might be simpler—and certainly cleaner—to just add all of the objects to a list and then json.dumps that list:

output = []
for task in l:
    if (task['Name'] == 'dinner'):  #criteria for desirable tasks
        output.append(task)
a.write(json.dumps(output))

Or, more simply:

json.dump([task for task in l if task['Name'] == 'dinner'], a)

(In fact, even if memory is an issue, you can extend JSONEncoder, as shown in the docs, to handle iterators by converting them lazily into JSON arrays, but this is a bit tricky, so I won't show the details unless someone needs them.)