當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Python复杂对象转JSON
生活随笔
收集整理的這篇文章主要介紹了
Python复杂对象转JSON
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Python復(fù)雜對象轉(zhuǎn)JSON
在Python對于簡單的對象轉(zhuǎn)json還是比較簡單的,如下:
import jsond = {'a': 'aaa', 'b': ['b1', 'b2', 'b3'], 'c': 100} json_str = json.dumps(d) print json_str對于復(fù)雜對象,可以使用下面的方法來實現(xiàn),比如:
import jsonclass Customer: def __init__(self, name, grade, age, home, office): self.name = name self.grade = grade self.age = age self.address = Address(home, office)def __repr__(self): return repr((self.name, self.grade, self.age, self.address.home, self.address.office)) class Address:def __init__(self, home, office):self.home = homeself.office = officedef __repr__(self): return repr((self.name, self.grade, self.age))customers = [ Customer('john', 'A', 15, '111', 'aaa'), Customer('jane', 'B', 12, '222', 'bbb'), Customer('dave', 'B', 10, '333', 'ccc'), ]json_str = json.dumps(customers, default=lambda o: o.__dict__, sort_keys=True, indent=4) print json_str結(jié)果如下
[{"address": {"home": "111", "office": "aaa"}, "age": 15, "grade": "A", "name": "john"}, {"address": {"home": "222", "office": "bbb"}, "age": 12, "grade": "B", "name": "jane"}, {"address": {"home": "333", "office": "ccc"}, "age": 10, "grade": "B", "name": "dave"} ]轉(zhuǎn)載請以鏈接形式標(biāo)明本文地址
本文地址:http://blog.csdn.net/kongxx/article/details/51563720
總結(jié)
以上是生活随笔為你收集整理的Python复杂对象转JSON的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ分类-转载
- 下一篇: 统计iOS项目的总代码行数的方法