2011-02-03 20 views
1

我正在查看json documentation,我試圖瞭解如何將Python對象實際轉換爲JSON數據,然後將該數據轉換回Python對象。我知道你可以通過列表,字典和元組的頂部的例子,但我嘗試創建一個非常小的對象,並將其傳遞給json.dumps()並得到「對象不是JSON可序列化」。Python中的JSON用法

什麼是使對象JSON可序列化的正確方法?我目前正在想象編寫一個方法,將我的對象轉換成字典,然後將其傳遞給json.dump()和一個並行方法來獲取字典並從中構造一個新對象。然而,這似乎真的是多餘的和有限的,所以我覺得我一定會有一些我想念的東西。任何人都可以幫我填補嗎?

+0

回覆:[best-practice]標記:http://meta.stackexchange.com/questions/60118/tag-block-request-best-practice – 2011-02-03 02:48:16

+0

啊哈,我想這將是一個相當無用的標記回顧。 – dimo414 2011-02-03 02:54:46

回答

0

以下代碼片斷說明了在Python 3中使用JSON的幾個方面。請注意JSONEncoder類以及編碼decimal和datetime的實現。

import json 
from decimal import Decimal 
from datetime import datetime, date 

class JSONEncoder(json.JSONEncoder): 
    def default(self, o): 
    if isinstance(o, Decimal): 
     return float(o) 
    elif isinstance(o, (datetime, date)): 
     return o.isoformat() 
    return super().default(self,o) 

class JSONDecoder(json.JSONDecoder): 
    pass 

_Default_Encoder = JSONEncoder(
    skipkeys=False, 
    ensure_ascii=False, 
    check_circular=True, 
    allow_nan=True, 
    indent=None, 
    separators=None, 
    default=None, 
) 

_Default_Decoder = JSONDecoder(
    object_hook=None, 
    object_pairs_hook=None 
) 

Encode = _Default_Encoder.encode 
Decode = _Default_Decoder.decode