Skip to content

Instantly share code, notes, and snippets.

@igauravsehrawat
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igauravsehrawat/36ece94ea4deef1fb502 to your computer and use it in GitHub Desktop.
Save igauravsehrawat/36ece94ea4deef1fb502 to your computer and use it in GitHub Desktop.
json.dumps() from class objects
#!/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