-
-
Save igauravsehrawat/36ece94ea4deef1fb502 to your computer and use it in GitHub Desktop.
json.dumps() from class objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python | |
#author class | |
import json | |
import simplejson | |
class Book(object) : | |
def __init__(self, name, isbn, price_in_usd) : | |
self.name = name | |
self.isbn = isbn | |
self.price_in_usd = price_in_usd | |
class Author(object) : | |
def __init__(self, name, email, books) : | |
self.name = name | |
self.email = email | |
self.books = books | |
author = Author( | |
name = u"Leslie Lamport", | |
email = u"lamport@microsoft.com", | |
books = [ | |
Book( | |
name = u"LaTeX: A document preparation system", | |
isbn = u"0201529831", | |
price_in_usd = 38.01 | |
), | |
Book( | |
name = u"Specifying Systems: The TLA+ Language", | |
isbn = u"032114306X", | |
price_in_usd = 40.73 | |
) | |
] | |
) | |
def book_to_json(b) : | |
data = { | |
"name": b.name, | |
"isbn": b.isbn, | |
"price_in_usd": b.price_in_usd | |
} | |
return json.dumps(data, indent=2) | |
author2 = Author( | |
name = u"Leslie Lamport", | |
email = u"lamport@microsoft.com", | |
books = [ | |
Book( | |
name = u"LaTeX: A document preparation system", | |
isbn = u"0201529831", | |
price_in_usd = 38.01 | |
), | |
Book( | |
name = u"Specifying Systems: The TLA+ Language", | |
isbn = u"032114306X", | |
price_in_usd = 40.73 | |
) | |
] | |
) | |
def author_to_json(author): | |
jobject ={ | |
"name": author.name , | |
"email": author.email , | |
"books" : [book_to_json(book) for book in author.books] | |
} | |
#list_comp = [to_JSON(book)for book in books] | |
return json.dumps(jobject) | |
print(author_to_json(author2)) | |
Output: | |
{"books": ["{\n \"price_in_usd\": 38.01, \n \"isbn\": \"0201529831\", \n \"name\": \"LaTeX: A document preparation system\"\n}", "{\n \"price_in_usd\": 40.73, \n \"isbn\": \"032114306X\", \n \"name\": \"Specifying Systems: The TLA+ Language\"\n}"], "name": "Leslie Lamport", "email": "lamport@microsoft.com"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment