鱼C论坛

 找回密码
 立即注册
查看: 2273|回复: 0

[作品展示] json格式化输出

[复制链接]
发表于 2022-8-6 21:32:49 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 鱼cpython学习者 于 2022-8-6 21:34 编辑

自己实现的json格式化
数据
  1. a = {"glossary": {"title": "example glossary","GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML", "XML"]},"GlossSee": "markup"}}}}}
复制代码

代码
  1. def format_json(array, level=0):
  2.     result = ''
  3.     if isinstance(array, dict):
  4.         if not array:
  5.             result += '{}'
  6.         result += '\n'
  7.         for key, value in array.items():
  8.             result += '\t' * level + key + ": " + format_json(value, level + 1)
  9.         return result
  10.     elif isinstance(array, list):
  11.         return format_json({f'[{index}]': item for index, item in enumerate(array)}, level)
  12.     else:
  13.         return result + repr(array) + '\n'
复制代码

输出

  1. glossary:
  2.         title: 'example glossary'
  3.         GlossDiv:
  4.                 title: 'S'
  5.                 GlossList:
  6.                         GlossEntry:
  7.                                 ID: 'SGML'
  8.                                 SortAs: 'SGML'
  9.                                 GlossTerm: 'Standard Generalized Markup Language'
  10.                                 Acronym: 'SGML'
  11.                                 Abbrev: 'ISO 8879:1986'
  12.                                 GlossDef:
  13.                                         para: 'A meta-markup language, used to create markup languages such as DocBook.'
  14.                                         GlossSeeAlso:
  15.                                                 [0]: 'GML'
  16.                                                 [1]: 'XML'
  17.                                 GlossSee: 'markup'

复制代码

使用line_profile分析性能时间为0.0003052 s
  1. Timer unit: 1e-06 s

  2. Total time: 0.0003052 s
  3. File: .\json_formater.py
  4. Function: format_json at line 6

  5. Line #      Hits         Time  Per Hit   % Time  Line Contents
  6. ==============================================================
  7.      6                                           @profile
  8.      7                                           def format_json(array, level=0):
  9.      8        19         15.9      0.8      5.2      result = ''
  10.      9        19        164.0      8.6     53.7      if isinstance(array, dict):
  11.     10         7          6.0      0.9      2.0          if not array:
  12.     11                                                       result += '{}'
  13.     12         7          5.6      0.8      1.8          result += '\n'
  14.     13        24         27.9      1.2      9.1          for key, value in array.items():
  15.     14        17         44.2      2.6     14.5              result += '\t' * level + key + ": " + format_json(value, level + 1)
  16.     15         7          5.2      0.7      1.7          return result
  17.     16        12         10.8      0.9      3.5      elif isinstance(array, list):
  18.     17         1          8.2      8.2      2.7          return format_json({f'[{index}]': item for index, item in enumerate(array)}, level)
  19.     18                                               else:
  20.     19        11         17.4      1.6      5.7          return result + repr(array) + '\n'
复制代码

加上输出变为 0.0008409 s
  1. Timer unit: 1e-06 s

  2. Total time: 0.0008409 s
  3. File: .\json_formater.py
  4. Function: printj at line 22

  5. Line #      Hits         Time  Per Hit   % Time  Line Contents
  6. ==============================================================
  7.     22                                           @profile
  8.     23                                           def test():
  9.     24         1        840.9    840.9    100.0      print(format_json(a))
复制代码

使用python标准库json实现的效果:
  1. print(json.dumps(a, sort_keys=True, indent=4, separators=(',', ': ')))
  2. {
  3.     "glossary": {
  4.         "GlossDiv": {
  5.             "GlossList": {
  6.                 "GlossEntry": {
  7.                     "Abbrev": "ISO 8879:1986",
  8.                     "Acronym": "SGML",
  9.                     "GlossDef": {
  10.                         "GlossSeeAlso": [
  11.                             "GML",
  12.                             "XML"
  13.                         ],
  14.                         "para": "A meta-markup language, used to create markup languages such as DocBook."
  15.                     },
  16.                     "GlossSee": "markup",
  17.                     "GlossTerm": "Standard Generalized Markup Language",
  18.                     "ID": "SGML",
  19.                     "SortAs": "SGML"
  20.                 }
  21.             },
  22.             "title": "S"
  23.         },
  24.         "title": "example glossary"
  25.     }
  26. }
复制代码

line_profile分析0.0014262 s
  1. Timer unit: 1e-06 s

  2. Total time: 0.0014262 s
  3. File: .\json_formater.py
  4. Function: printj at line 22

  5. Line #      Hits         Time  Per Hit   % Time  Line Contents
  6. ==============================================================
  7.     22                                           @profile
  8.     23                                           def test():
  9.     24         1       1426.2   1426.2    100.0      print(json.dumps(a, sort_keys=True, indent=4, separators=(',', ': ')))
复制代码

虽然快不了多少,但对于我这个菜鸡来说还是值得庆祝的
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-23 17:38

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表