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 OverflowYou 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)
Similar to @MartijnPieters' answer, you can use the json.dumps default parameter with a lambda, if you don't want to have to create a separate function:
json.dumps(obj, default = lambda x: x.__dict__)
Convert JSON array to Python list - Stack Overflow
Python Convert JSON Array to Corresponding List of Python Objects - Stack Overflow
Elegant way to convert json to list of objects in Python 3 - Stack Overflow
convert list of dictionary to list of json objects
Videos
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
print(data['fruits'])
# the print displays:
# ['apple', 'banana', 'orange']
You had everything you needed. data will be a dict, and data['fruits'] will be a list
Tested on Ideone.
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
fruits_list = data['fruits']
print fruits_list
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
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)
How to convert list of dictionary to list of json objects?
input = [{'a':'b'},{'c':'d'}]
expectedOutput = [{"a":"b"},{"c":"d"}]
I tried following but couldn't get expected result
-
json.dumps(input)gives string'[{"a":"b"},{"c":"d"}]' -
Iterate through dictionary and convert each dict to json object gives
['{"a":"b"}','{"c":"d"}']
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.
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()
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.)