相关疑难解决方法(0)

如何更改可序列化python对象的json编码行为?

很容易更改不是JSON可序列化的对象的格式,例如datetime.datetime.

出于调试目的,我的要求是改变一些自定义对象从基本对象扩展的方式,dictlist以json格式进行序列化.代码:

import datetime
import json

def json_debug_handler(obj):
    print("object received:")
    print type(obj)
    print("\n\n")
    if  isinstance(obj, datetime.datetime):
        return obj.isoformat()
    elif isinstance(obj,mDict):
        return {'orig':obj , 'attrs': vars(obj)}
    elif isinstance(obj,mList):
        return {'orig':obj, 'attrs': vars(obj)}
    else:
        return None


class mDict(dict):
    pass


class mList(list):
    pass


def test_debug_json():
    games = mList(['mario','contra','tetris'])
    games.src = 'console'
    scores = mDict({'dp':10,'pk':45})
    scores.processed = "unprocessed"
    test_json = { 'games' : games , 'scores' : scores , 'date': datetime.datetime.now() }
    print(json.dumps(test_json,default=json_debug_handler))

if __name__ == '__main__':
    test_debug_json()
Run Code Online (Sandbox Code Playgroud)

演示:http …

python json

58
推荐指数
4
解决办法
1万
查看次数

使用Python> = 2.7将嵌套的namedtuple序列化为JSON

我遇到类似于CalvinKrishy问题的问题 Samplebias的解决方案不能处理我的数据.

我使用的是Python 2.7.

这是数据:

Namedtuple

>>> a_t = namedtuple('a','f1 words')
>>> word_t = namedtuple('word','f2 value')
>>> w1 = word_t(f2=[0,1,2], value='abc')
>>> w2 = word_t(f2=[3,4], value='def')
>>> a1 = a_t(f1=[0,1,2,3,4],words=[w1, w2])
>>> a1
a(f1=[0, 1, 2, 3, 4], words=[word(f2=[0, 1, 2], value='abc'), word(f2=[3, 4], value='def')])
Run Code Online (Sandbox Code Playgroud)

快译通

>>> w3 = {}
>>> w3['f2'] = [0,1,2]
>>> w3['value'] = 'abc'
>>> w4 = {}
>>> w4['f2'] = [3,4]
>>> w4['value'] = 'def'
>>> a2 = {}
>>> a2['f1'] = [0, 1, …
Run Code Online (Sandbox Code Playgroud)

python json namedtuple python-2.7

9
推荐指数
1
解决办法
4044
查看次数

标签 统计

json ×2

python ×2

namedtuple ×1

python-2.7 ×1