-
-
Save igauravsehrawat/e7d62fb9b7263ce67ad6 to your computer and use it in GitHub Desktop.
working json
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 | |
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 | |
def jsonable(self): | |
return self.__dict__ | |
def reprJSON(self): | |
return dict(name=self.name, email=self.email,books=[dict(name=book.name,isbn=book.isbn,price_in_usd=book.price_in_usd) for book in author.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 | |
) | |
] | |
) | |
class ComplexEncoder(json.JSONEncoder): | |
def default(self, obj): | |
if hasattr(obj,'reprJSON'): | |
return obj.reprJSON() | |
else: | |
return json.JSONEncoder.default(self, obj) | |
def ComplexHandler(Obj): | |
if hasattr(Obj, 'jsonable'): | |
return Obj.jsonable() | |
else: | |
raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(Obj), repr(Obj)) | |
def author_to_json(author): | |
jobject ={ | |
"name": author.name , | |
"email": author.email , | |
"books" : [book_to_json(book) for book in author.books] | |
} | |
jobject2 = { | |
"name": author.name , | |
"email": author.email , | |
"books" : author.books | |
} | |
#list_comp = [to_JSON(book)for book in books] | |
#print json.dumps(jobject) | |
print json.dumps(author.reprJSON()) | |
return json.dumps(author2.reprJSON(), default=ComplexHandler ) | |
#return json.dumps(name,email,books_to_json(books) | |
#return author.to_JSON | |
print(author_to_json(author2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment