zoukankan      html  css  js  c++  java
  • Python下将一般对象打印成Json

      版权申明:本文为博主窗户(Colin Cai)原创,欢迎转帖。如要转贴,必须注明原文网址
    
      http://www.cnblogs.com/Colin-Cai/p/12741423.html 
    
      作者:窗户
    
      QQ/微信:6679072
    
      E-mail:6679072@qq.com

      有的时候,我们写Python程序需要处理复杂对象,过程中调试可能需要去看看产生的对象如何,我们可以把它打印成json来看,这是个不错的办法。

      对每一个对象写一个独立的打印成json的程序是个不能复用的工作,我们可以考虑通用的写法,好在Python的反射可以帮我们做到这一点,以下为我晚上所写,所有的成员名字按字典排布打印。

    from functools import reduce
    make_json = lambda blanks,obj : 
    (lambda t, cut : 
      'null' if obj==None 
      else str(obj) if t in (int,float) 
      else ('true' if obj else 'false') if t==bool 
      else '"%s"'%obj if t==str 
      else '[' + cut(reduce(lambda r,x:r+',
    '+' '*(blanks+2)+make_json(blanks+2,x), obj, '')) 
        + '
    ' + ' '*blanks + ']' if t in (list, tuple) 
      else '{' + cut(reduce(lambda r,x:r+',
    '+' '*(blanks+2)+'"%s" : '%x+make_json(blanks+2,obj[x]), 
        sorted(filter(lambda x:type(x)==str,obj.keys())), '')) + '
    ' + ' '*blanks + '}' if t==dict 
      else reduce(lambda r,x:r+'%02x'%x, list(map(int, obj)),'"')+'"' if t==bytes 
      else '{' + cut(reduce(lambda r,x:
        r+',
    '+' '*(blanks+2)+'"%s" : '%x+make_json(blanks+2,obj.__dict__[x]), 
        sorted(filter(lambda x:len(x)<4 or x[:2]!='__' 
          or x[-2:]!='__',obj.__dict__.keys())), '')) + '
    ' + ' '*blanks + '}') 
    (type(obj), lambda x:x if x=='' else x[1:])
    
    print_json = lambda obj, fprint : fprint(make_json(0, obj))

      以上的print_json就是打印json的函数,fprint是一个接打印字符串的函数,这里你当然可以随便打印到哪里。

      我们测试如下:

    class class1:
      def __init__(self):
        self.a1 = None
        self.b1 = None
        self.c1 = None
    
    class class2:
      def __init__(self):
        self.a2 = None
        self.b2 = None
        self.c2 = None
    
    class class3:
      def __init__(self):
        self.a3 = None
        self.b3 = None
        self.c3 = None
    
    test_obj = class1()
    test_obj.a1 = [1, None, 2.5, class2(), True]
    test_obj.a1[3].a2 = [class3(), class3()]
    test_obj.a1[3].a2[0].a3 = [1, 2, 3]
    test_obj.a1[3].a2[0].b3 = ["test1", "test2"]
    test_obj.a1[3].a2[0].c3 = None
    test_obj.a1[3].a2[1].a3 = [5, 6, 7]
    test_obj.a1[3].a2[1].b3 = ["test3", "test4"]
    test_obj.a1[3].a2[1].c3 = [True, False]
    test_obj.a1[3].b2 = {"x":1, "y":2}
    test_obj.a1[3].c2 = type('', (), {"x":10, "y":20})
    test_obj.b1 = 100
    test_obj.c1 = "test"
    print_json(test_obj, print)

      以上构建了一个test_obj对象,并打印出来。

    {
      "a1": [
        1,
        null,
        2.5,
        {
          "a2": [
            {
              "a3": [
                1,
                2,
                3
              ],
              "b3": [
                "test1",
                "test2"
              ],
              "c3": null
            },
            {
              "a3": [
                5,
                6,
                7
              ],
              "b3": [
                "test3",
                "test4"
              ],
              "c3": [
                true,
                false
              ]
            }
          ],
          "b2": {
            "x": 1,
            "y": 2
          },
          "c2": {
            "x": 10,
            "y": 20
          }
        },
        true
      ],
      "b1": 100,
      "c1": "test"
    }

      这是一个标准的json,显然print_json函数是可用的。Python2里print是个命令,所以需要包装成一下。

      如果上述想打印到文件,你可以

    json_file = open('test_obj.json', 'w')
    print_json(test_obj, lambda s:print(s, file=json_file))
    json_file.close()

      

      声明:以上代码作者是我本人(Colin Cai),可以随便使用,不受任何约束,如出现任何错误与损失均和笔者无任何关系! 

  • 相关阅读:
    两个泛型实例之间的属性变化
    C#
    字符编码
    如何在阿里云 CentOS 8 / RHEL 8 上安装 vsftpd(ftp 服务器)
    使用 ASP.NET Core 创建 Web API使用 JavaScript 调用报错 webapi Unable to get items. TypeError: Failed to fetch
    让WPF程序启动时以管理员身份运行(转载)
    WPF任务栏同步进度
    C# ref and out
    C# 中 string.Empty、""、null的差别
    如何读写拥有命名空间xmlns 属性的Xml文件(C#实现)
  • 原文地址:https://www.cnblogs.com/Colin-Cai/p/12741423.html
Copyright © 2011-2022 走看看