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+',\n'+' '*(blanks+2)+make_json(blanks+2,x), obj, '')) \
    + '\n' + ' '*blanks + ']' if t in (list, tuple) \
  else '{' + cut(reduce(lambda r,x:r+',\n'+' '*(blanks+2)+'"%s" : '%x+make_json(blanks+2,obj[x]), \
    sorted(filter(lambda x:type(x)==str,obj.keys())), '')) + '\n' + ' '*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+',\n'+' '*(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())), '')) + '\n' + ' '*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),可以隨便使用,不受任何約束,如出現任何錯誤與損失均和筆者無任何關系! 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM