Python Json转储不打印值

时间:2017-08-10 14:12:11

标签: json python-2.7

我正在尝试一个简单的程序

import json

class unified_response():
trinitiversion="3"
preprocess = []

if __name__ == '__main__':
 ur = unified_response()
 preprocessValDict = dict()
 preprocessValDict["input"] = "some string"
 preprocessValDict["correct"] = " correct some string"
 ur.preprocess.append(preprocessValDict)

 s = json.dumps(unified_response.__dict__)
 print s
 s = json.dumps(ur.__dict__)
 print s

打印第一个打印语句

{"preprocess": [{"input": "some string", "correct": " correct some string"}], "trinitiversion": "3", "__module__": "__main__", "__doc__": null}

打印第二个print语句

{}

为什么第二个对象不打印任何值?

1 个答案:

答案 0 :(得分:0)

这与json模块完全无关。

ur.__dict__是一个空字典,因为实例中只保存了实例属性。

unified_response类只有类属性,因此ur.__dict__是一个空字典,json.dumps转换为空字符串。

比较print unified_response.__dict__print ur.__dict__的输出。


作为旁注:

ur.preprocess.append(preprocessValDict)

通过实例访问(尤其是修改)类属性被认为是一种不好的做法,因为它可能导致难以发现的错误。