定义一个Python class
class Node:
def __init__(self):
self.ip = ""
self.pods = []
self.count = 0
Json 对象(instance) 转 dict 和字符串
n = Node()
n.count = 1
n.ip = "127.0.0.1"
n.pods = ["pod-x", "pod-y", "pod-z"]
# Json Object
print(n) # <__main__.Node instance at 0x7f4eaa078eb0>
print(n.ip)
print(type(n)) # <type 'instance'>
# Json Object to Dict
print(n.__dict__)
print(n.__dict__["ip"])
# Json Object to String
json_str = json.dumps(n.__dict__, indent = 4)
print(json_str)
Json dict 按特定key的value 排序
n1 = Node()
n1.count = 2
n1.ip = "127.0.0.2"
n1.pods = ["pod-x2", "pod-y2"]
n2 = Node()
n2.count = 3
n2.ip = "127.0.0.2"
n2.pods = ["pod-x3", "pod-y3", "pod-z3"]
nodes = [n, n1, n2]
# json object array to string
nodes_jsonstr = json.dumps(nodes, default = lambda o : o.__dict__, indent=4)
print(nodes_jsonstr)
print(type(nodes_jsonstr)) # <type 'str'>
# json string to dict
json.loads(nodes_jsonstr)
# dict sort
nodes_array = sorted(json.loads(nodes_jsonstr), key = lambda e : e["count"], reverse = False)
print(nodes_array[0])
print(nodes_array[0]['ip'])
print(type(nodes_array[0])) # <type 'dict'>
dict似乎无法直接转为Json Object, 但可以实现. 方法
class Dict(dict):
__setattr__ = dict.__setitem__
__getattr__ = dict.__getitem__
def dictToObj(dictObj):
if not isinstance(dictObj, dict):
return dictObj
d = Dict()
for k, v in dictObj.items():
d[k] = dictToObj(v)
return d
n_obj = dictToObj(nodes_array[0])
print(n_obj.ip)
print(type(n_obj)) # <class '__main__.Dict'>