Python Objects to JSON String
Python provides a easy way to handle JSON, by importing thejson module, one can easily encode a list of dicts or a dict of dicts so on, but there is a easy trick to generate a JSON or even a nested JSON string from an object of a class.
json.dumps(obj[, skipkeys[, ensure_ascii[, check_circular[, allow_nan[, cls[, indent[, separators[, encoding[, default[, **kw]]]]]]]]]])`=> Serialize obj to a JSON formatted str
Consider an example, classic class called Student with few attributes like email,contact,name,skills,edu. Which are updated by other methods or at object creation.
class Student:
def init(self,name,email,contact,skills,ug=None,pg=None):
self.email=email
self.contact=contact
self.name=name
self.skills=[skills]
self.edu={"ug":[ug],"pg":[pg]}
Creating an instance of that class and prints the vars() we get something like :
james=Student("James","[email protected]","","+1 7789990007","Python","CS", "CS")
print vars(james) {
'skills': ['Python'],
'contact': '+1 7789990007',
'email': '[email protected]',
'edu': {
'ug': ['CS'],
'pg': ['CS']
},
'name': 'James'
}
import json print json.dumps(vars(james),sort_keys=True, indent=4)
{
"contact": "+1 7789990007",
"edu": {
"pg": [
"CS"
],
"ug": [
"CS"
]
},
"email": "[email protected]",
"name": "James",
"skills": [
"Python Ruby"
]
}
P.S : This is just on the ways to Serialize obj to a JSON formatted str. Do share your ways below!
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.