当前位置:   article > 正文

Python:Json与Markdown互相转换_json转markdown

json转markdown

目录

一、Json转Markdown

1、原始torsimany库

2、torsimany库修改

二、Markdown转Json


因为一些特殊场景的需要,需要将接口的json返回渲染成markdown形式,自己处理的话还挺麻烦的,俗话说的好:站在巨人的肩膀上。下面介绍了基于Python的Json与Markdown互相转换的方式,当然你可以在Github上多搜搜看看其它的方案。

一、Json转Markdown

1、原始torsimany库

https://github.com/PolBaladas/torsimany

 安装依赖库:torsimany

pip3 install torsimany

使用方式:

  1. python3 torsimany.py [JSON_FILE].json
  2. 或者
  3. torsimany [JSON_FILE].json

假设我们有个Json格式文件:products.json,内容如下:

  1. {
  2. "name":"Product",
  3. "properties":
  4. {
  5. "id":
  6. {
  7. "type":"number",
  8. "description":"Product identifier",
  9. "required":true
  10. },
  11. "name":
  12. {
  13. "description":"Name of the product",
  14. "type":"string",
  15. "required":true
  16. },
  17. "price":
  18. {
  19. "type":"number",
  20. "minimum":0,
  21. "required":true
  22. },
  23. "tags":
  24. {
  25. "type":"array",
  26. "items":
  27. {
  28. "type":"string"
  29. }
  30. }
  31. }
  32. }

我们在终端执行如下命令,将其转化为Markdown格式文件:

torsimany products.json

如果在Python3报错:AttributeError: 'str' object has no attribute 'decode'

解决方法:可以尝试修改下安装包对应的文件:./site-packages/torsimany/torsimany.py,修改内容如下:

预期成功的话,会在当前目录生成:products.markdown文件,也就是markdown形式的文件,内容如下:

  1. * name: Product
  2. # Properties #
  3. * ## Id ##
  4. * type: number
  5. * description: Product identifier
  6. * required: True
  7. * ## Name ##
  8. * description: Name of the product
  9. * type: string
  10. * required: True
  11. * ## Price ##
  12. * type: number
  13. * minimum: 0
  14. * required: True
  15. * ## Tags ##
  16. * type: array
  17. * ### Items ###
  18. * type: string

我们通过Markdown在线工具查看效果,大概如下:

2、torsimany库修改

上述的torsimany库默认只支持文件形式的转换,其实我们日常用的比较多的是直接在线转换json文件为mardkdown的形式,于是对上面的实现进行了一些简单的改动,其实也比较简单,就一个文件,json2markdown.py

  1. # -*- coding: UTF-8 -*-
  2. """
  3. @Function:json to markdown
  4. @Time : 2022/6/15 09:45
  5. @Auth : https://github.com/PolBaladas/torsimany/blob/master/torsimany/torsimany.py
  6. """
  7. import sys
  8. import json
  9. class Json2Markdown(object):
  10. """
  11. # json转markdown形式
  12. """
  13. def __init__(self):
  14. self.markdown = ""
  15. self.tab = " "
  16. self.list_tag = '* '
  17. self.htag = '#'
  18. def loadJSON(self, file):
  19. """
  20. :param file:
  21. :return:
  22. """
  23. with open(file, 'r') as f:
  24. data = f.read()
  25. return json.loads(data)
  26. def parseJSON(self, json_block, depth):
  27. """
  28. :param json_block:
  29. :param depth:
  30. :return:
  31. """
  32. if isinstance(json_block, dict):
  33. self.parseDict(json_block, depth)
  34. if isinstance(json_block, list):
  35. self.parseList(json_block, depth)
  36. def parseDict(self, d, depth):
  37. """
  38. :param d:
  39. :param depth:
  40. :return:
  41. """
  42. for k in d:
  43. if isinstance(d[k], (dict, list)):
  44. self.addHeader(k, depth)
  45. self.parseJSON(d[k], depth + 1)
  46. else:
  47. self.addValue(k, d[k], depth)
  48. def parseList(self, l, depth):
  49. """
  50. :param l:
  51. :param depth:
  52. :return:
  53. """
  54. for value in l:
  55. if not isinstance(value, (dict, list)):
  56. index = l.index(value)
  57. self.addValue(index, value, depth)
  58. else:
  59. self.parseDict(value, depth)
  60. def buildHeaderChain(self, depth):
  61. """
  62. :param depth:
  63. :return:
  64. """
  65. chain = self.list_tag * (bool(depth)) + self.htag * (depth + 1) + \
  66. ' value ' + (self.htag * (depth + 1) + '\n')
  67. return chain
  68. def buildValueChain(self, key, value, depth):
  69. """
  70. :param key:
  71. :param value:
  72. :param depth:
  73. :return:
  74. """
  75. chain = self.tab * (bool(depth - 1)) + self.list_tag + \
  76. str(key) + ": " + str(value) + "\n"
  77. return chain
  78. def addHeader(self, value, depth):
  79. """
  80. :param value:
  81. :param depth:
  82. :return:
  83. """
  84. chain = self.buildHeaderChain(depth)
  85. self.markdown += chain.replace('value', value.title())
  86. def addValue(self, key, value, depth):
  87. """
  88. :param key:
  89. :param value:
  90. :param depth:
  91. :return:
  92. """
  93. chain = self.buildValueChain(key, value, depth)
  94. self.markdown += chain
  95. def json2markdown(self, json_data):
  96. """
  97. :param json_data:
  98. :return:
  99. """
  100. depth = 0
  101. self.parseJSON(json_data, depth)
  102. self.markdown = self.markdown.replace('#######', '######')
  103. return self.markdown
  104. if __name__ == '__main__':
  105. json_data = [
  106. {
  107. "scene": "气泡触发次数过高(1小时)",
  108. "data": [
  109. ]
  110. },
  111. {
  112. "scene": "重点人触发气泡过多(1小时)",
  113. "data": [
  114. ]
  115. },
  116. {
  117. "scene": "某一气泡CTR过低(1天)",
  118. "data": [
  119. "马家春慢#0#60#0.0",
  120. "法曲献仙音#1#135#0.007",
  121. "月宫春#0#91#0.0",
  122. "海棠花令#0#97#0.0"
  123. ]
  124. }
  125. ]
  126. # 实例
  127. json2markdown_ins = Json2Markdown()
  128. # json转markdown
  129. markdown_data = json2markdown_ins.json2markdown(json_data)
  130. print(markdown_data)
'
运行

试运行下,结果如下:

  1. $ python3 json2markdown.py
  2. * scene: 气泡触发次数过高(1小时)
  3. # Data #
  4. * scene: 重点人触发气泡过多(1小时)
  5. # Data #
  6. * scene: 某一气泡CTR过低(1天)
  7. # Data #
  8. * 0: 马家春慢#0#60#0.0
  9. * 1: 法曲献仙音#1#135#0.007
  10. * 2: 月宫春#0#91#0.0
  11. * 3: 海棠花令#0#97#0.0

 通过Markdown在线工具看下转换后的markdown数据:

二、Markdown转Json

https://github.com/njvack/markdown-to-json

安装依赖库:markdown-to-json

pip3 install markdown-to-json

使用方法:

  1. $ md_to_json -h
  2. Translate markdown into JSON.
  3. Usage:
  4. md_to_json [options] <markdown_file>
  5. md_to_json -h | --help
  6. Options:
  7. -h --help Show this screen
  8. --version Print version number
  9. -o <file> Save output to a file instead of stdout
  10. -i <val> Indent nested JSON by this amount. Use a negative number for
  11. most compact possible JSON. the [default: 2]

我们以products.markdown文件为例(上文生成的),命令如下,当然也可以通过-o指定写入到生成的文件。

  1. $ md_to_json products1.markdown
  2. # 输出结果
  3. {
  4. "Properties": [
  5. "Id",
  6. [
  7. "type: number",
  8. "description: Product identifier",
  9. "required: True"
  10. ],
  11. "Name",
  12. [
  13. "description: Name of the product",
  14. "type: string",
  15. "required: True"
  16. ],
  17. "Price",
  18. [
  19. "type: number",
  20. "minimum: 0",
  21. "required: True"
  22. ],
  23. "Tags",
  24. [
  25. "type: array"
  26. ],
  27. "Items",
  28. [
  29. "type: string"
  30. ]
  31. ]
  32. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/822857
推荐阅读
相关标签
  

闽ICP备14008679号