国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現復雜對象轉JSON的方法示例

2020-01-04 16:53:29
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現復雜對象轉JSON的方法。分享給大家供大家參考,具體如下:

在Python對于簡單的對象轉json還是比較簡單的,如下:

import jsond = {'a': 'aaa', 'b': ['b1', 'b2', 'b3'], 'c': 100}json_str = json.dumps(d)print json_str

對于復雜對象,可以使用下面的方法來實現,比如:

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 = home    self.office = office  def __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

結果如下

[  {    "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"  }]

希望本文所述對大家Python程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宁陕县| 临沭县| 南乐县| 安义县| 栾城县| 玛多县| 嘉义县| 化州市| 房山区| 平湖市| 门源| 河间市| 抚宁县| 通化县| 南涧| 宁蒗| 邢台市| 宝丰县| 宝应县| 林甸县| 广东省| 岳普湖县| 桃园市| 双柏县| 淮南市| 越西县| 乳山市| 同德县| 玉田县| 沂南县| 阿巴嘎旗| 栖霞市| 九龙县| 新乐市| 临潭县| 凌云县| 铜鼓县| 呼和浩特市| 五华县| 黔南| 德化县|