Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tierpod
Created February 7, 2018 14:10
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 tierpod/85ca3650955f8beddf81ab76243fca48 to your computer and use it in GitHub Desktop.
Save tierpod/85ca3650955f8beddf81ab76243fca48 to your computer and use it in GitHub Desktop.
json to python class example
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os.path
def md5sum():
return "test"
class File(object):
def __init__(self, md5=None, filename=None):
self.md5 = md5 or md5sum()
self.filename = os.path.basename(filename)
def __str__(self):
return "File(md5={}, filename={})".format(self.md5, self.filename)
@classmethod
def from_json(cls, md5, filename):
return cls(md5=md5, filename=filename)
def to_json(self):
return {
"MD5": self.md5,
"Filename": self.filename,
}
def __eq__(self, other):
return self.filename == other.filename
string = """[{"MD5": "3123", "Filename": "test"}]"""
json_items = json.loads(string)
print(json_items)
print("convert json list to list of File")
#items = []
#for i in json_items:
# items.append(File.from_json(md5=i["MD5"], filename=i["Filename"]))
items = [File.from_json(md5=i["MD5"], filename=i["Filename"]) for i in json_items]
del(json_items)
print(items)
print("create new test File objects")
f = File(filename="test")
f2 = File(filename="test")
print(f)
print(f == f2)
print("check if f in items")
print(f in items)
items.remove(f)
print(items)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment