Last active
January 8, 2017 16:43
-
-
Save LuqueDaniel/8730346 to your computer and use it in GitHub Desktop.
Serialize python objet to 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
# coding: utf-8 | |
import json | |
class UserEncoder(json.JSONEncoder): | |
def default(self, obj): | |
return obj.__dict__ | |
class User(object): | |
def __init__(self, username, password): | |
self.username = username | |
self.password = password | |
david = User("David", "password") | |
#Serializamos el objeto, el parametro cls corresponde al encoder que queramos usar | |
#En nuestro caso UserEncoder | |
serialize = json.dumps(david, cls=UserEncoder, indent=4) | |
#un print rápidito | |
print serialize |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment