我试图创建一个类实例的JSON字符串表示,有困难。假设这个类是这样构建的:

class testclass:
    value1 = "a"
    value2 = "b"

对json的调用。转储是这样的:

t = testclass()
json.dumps(t)

它失败了,告诉我测试类不是JSON序列化的。

TypeError: <__main__.testclass object at 0x000000000227A400> is not JSON serializable

我也尝试过使用pickle模块:

t = testclass()
print(pickle.dumps(t, pickle.HIGHEST_PROTOCOL))

它提供类实例的信息,而不是类实例的序列化内容。

b'\x80\x03c__main__\ntestclass\nq\x00)\x81q\x01}q\x02b.'

我做错了什么?


当前回答

你可以尝试objprint,这是一个轻量级的库,用于打印Python对象,它支持json输出。

pip install objprint
from objprint import objjson
t = testclass()
json_obj = objjson(t)
print(json.dumps(json_obj))

objjson基本上将任意对象转换为jsoniizable对象,如果它不是dict, list等内置类型,则它的原始Python类型有一个特殊的键.type。

如果只是想打印它,可以使用op,它通常用于以人类可读的格式打印对象。

from objprint import op
t = testclass()
op(t, format="json", indent=2)

# If you want to dump to a file
with open("my_obj.json", "w") as f:
    # This is the same usage as print
    op(t, format="json", file=f)

其他回答

我只会:

data=json.dumps(myobject.__dict__)

这不是完整的答案,如果你有某种复杂的对象类,你肯定不会得到所有的东西。然而,我在一些简单的对象中使用这种方法。

它工作得非常好的一个是您从OptionParser模块中获得的“options”类。 下面是它和JSON请求本身。

  def executeJson(self, url, options):
        data=json.dumps(options.__dict__)
        if options.verbose:
            print data
        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
        return requests.post(url, data, headers=headers)

JSON实际上并不用于序列化任意的Python对象。它非常适合序列化dict对象,但pickle模块才是你真正应该使用的。pickle的输出实际上不是人类可读的,但它应该可以解腌。如果坚持使用JSON,可以查看jsonpickle模块,这是一种有趣的混合方法。

https://github.com/jsonpickle/jsonpickle

你可以尝试objprint,这是一个轻量级的库,用于打印Python对象,它支持json输出。

pip install objprint
from objprint import objjson
t = testclass()
json_obj = objjson(t)
print(json.dumps(json_obj))

objjson基本上将任意对象转换为jsoniizable对象,如果它不是dict, list等内置类型,则它的原始Python类型有一个特殊的键.type。

如果只是想打印它,可以使用op,它通常用于以人类可读的格式打印对象。

from objprint import op
t = testclass()
op(t, format="json", indent=2)

# If you want to dump to a file
with open("my_obj.json", "w") as f:
    # This is the same usage as print
    op(t, format="json", file=f)

你可以在json.dumps()函数中指定默认的命名参数:

json.dumps(obj, default=lambda x: x.__dict__)

解释:

从文档(2.7,3.6):

``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.

(适用于Python 2.7和Python 3.x)

注意:在这种情况下,您需要实例变量而不是类变量,正如问题中的示例所尝试做的那样。(我假设请求者意味着类实例是类的对象)

我首先从@phihag的回答中了解到这一点。发现这是最简单、最干净的工作方式。

使用任意的可扩展对象,然后将其序列化为JSON:

import json

class Object(object):
    pass

response = Object()
response.debug = []
response.result = Object()

# Any manipulations with the object:
response.debug.append("Debug string here")
response.result.body = "404 Not Found"
response.result.code = 404

# Proper JSON output, with nice formatting:
print(json.dumps(response, indent=4, default=lambda x: x.__dict__))