python实现-从带层级的json到markdown无序列表的父子关系的转换

从带层级的json到无序列表的父子关系的转换

首先,我们需要查看JSON数据结构,然后将它转换成Markdown序列列表格式。

为了实现这个目标,我们可以编写一个递归函数来处理层级关系。

假设我们的JSON结构如下:


{
  "name": "思维导图",
  "children": [
    {
      "name": "主题1",
      "children": [
        {
          "name": "子主题1.1"
        },
        {
          "name": "子主题1.2"
        }
      ]
    },
    {
      "name": "主题2",
      "children": [
        {
          "name": "子主题2.1"
        }
      ]
    }
  ]
}  

我们可以使用以下递归函数将其转换为Markdown序列列表:


import json


def json_to_markdown(json_data, depth=0):
    markdown_output = ''
    if 'name' in json_data:        
        markdown_output += '  ' * depth + '- ' + json_data['name'] + '\n'
    if 'children' in json_data:        
        for child in json_data['children']: 
            markdown_output += json_to_markdown(child, depth + 1)
    return markdown_output


json_string = '''上述的JSON内容'''
json_data = json.loads(json_string)
markdown_output = json_to_markdown(json_data)

print(markdown_output)  

输出的Markdown序列列表格式如下:


- 思维导图
    - 主题1
        - 子主题1.1
        - 子主题1.2
    - 主题2
        - 子主题2.1  

这样,我们就可以将博文中的JSON数据转换成Markdown序列列表了。注意,你需要将上述代码中的json_string替换为实际的JSON数据。

我现在想把json文本放到文件里面, 但是我这个json文本很长, 我应该如何加载到python中, 才不会栈溢出, 然后使用递归转换成markdown格式的文本

您可以使用以下方法将JSON文本加载到Python中:

  1. 将JSON数据存储在一个名为json_data.json的文件中。
  2. 使用with语句和open()函数打开文件并将内容读取到一个变量中。
  3. 使用json.loads()函数将JSON文本转换为Python字典。

例如:


import json

# 读取JSON文件内容  
with open('json_data.json', 'r', encoding='utf-8') as file:
    json_string = file.read()
# 将JSON文本转换为Python字典  
json_data = json.loads(json_string)


# 使用先前提供的递归函数将JSON数据转换为Markdown  
def json_to_markdown(json_data, depth=0):
    markdown_output = ''
    if 'name' in json_data:
        markdown_output += '  ' * depth + '- ' + json_data['name'] + '\n'
    if 'children' in json_data:
        for child in json_data['children']:
            markdown_output += json_to_markdown(child, depth + 1)
            return markdown_output
        # 转换并打印输出的Markdown  


markdown_output = json_to_markdown(json_data)
print(markdown_output)  

至于栈溢出的问题,Python具有递归深度限制,这可能会导致栈溢出。为了解决这个问题,您可以通过设置较高的递归深度来尝试优化。不过请注意,设置过高的递归深度可能会导致内存不足的问题。下面是如何更改递归深度限制的示例:


import sys  

# 设置递归深度限制  
sys.setrecursionlimit(3000)  

在运行递归函数之前,您可以将上述代码添加到脚本中以提高递归深度限制。这将有助于避免栈溢出问题。然而,如果您的JSON数据结构非常大且层次非常深,您可能需要使用非递归方法来处理这种情况。

最后输出成一个 markdown
在已经生成Markdown序列列表的基础上,我们可以将其保存到一个Markdown文件中。以下是将markdown_output保存到名为output.md
的文件中的代码:


#将Markdown输出保存到文件

with open('output.md', 'w', encoding='utf-8') as file:  
    file.write(markdown_output)

将此代码添加到之前的Python脚本中,您将会得到一个完整的脚本,该脚本可以读取JSON文件,将其转换为Markdown序列列表,并将结果保存到名为output.md
的文件中。以下是完整的脚本:


import json  
import sys  

#设置递归深度限制

sys.setrecursionlimit(3000)  

#读取JSON文件内容

with open('json_data.json', 'r', encoding='utf-8') as file:  
    json_string = file.read()  

#将JSON文本转换为Python字典

json_data = json.loads(json_string)  

#使用递归函数将JSON数据转换为Markdown

def json_to_markdown(json_data, depth=0):  
    markdown_output = ''    
    if 'name' in json_data:        
        markdown_output += '  ' * depth + '- ' + json_data['name'] + '\n'    
    if 'children' in json_data:        
        for child in json_data['children']:            
            markdown_output += json_to_markdown(child, depth + 1)    
            return markdown_output  

#转换并打印输出的Markdown

markdown_output = json_to_markdown(json_data)  
print(markdown_output)  

#将Markdown输出保存到文件

with open('output.md', 'w', encoding='utf-8') as file:  
    file.write(markdown_output)

运行此脚本后,您会在脚本所在的目录下找到一个名为output.md的Markdown文件,其中包含转换后的序列列表。

总结

with open(‘output.md’, ‘w’, encoding=‘utf-8’) as file:
file.write(markdown_output)

with open(‘json_data.json’, ‘r’, encoding=‘utf-8’) as file:
json_string = file.read()
这两句, 主要是我不懂这两句的语法

这两个代码段使用Python的with语句和open()函数分别打开和处理文件。让我逐行解释这些代码段。

  1. with open('output.md', 'w', encoding='utf-8') as file:

这一行使用with语句和open()函数打开名为output.md的文件。'w'参数表示我们要以写入模式(write
mode)打开文件。这意味着如果文件已经存在,我们将覆盖它;如果文件不存在,我们将创建一个新文件。encoding='utf-8'
指定了文件的字符编码。as file表示我们将在with语句的块中使用变量名file引用打开的文件对象。

  1. file.write(markdown_output)

with语句的块中,我们使用write()方法将markdown_output变量的内容写入到文件中。在这种情况下,markdown_output
包含了我们之前从JSON数据生成的Markdown序列列表。

  1. with open('json_data.json', 'r', encoding='utf-8') as file:

类似于第一行,这一行使用with语句和open()函数打开名为json_data.json的文件。但是,这次我们使用'r'参数表示我们要以读取模式(read
mode)打开文件。这意味着我们将从文件中读取内容,而不是写入内容。encoding='utf-8'同样指定了文件的字符编码。as file
表示我们将在with语句的块中使用变量名file引用打开的文件对象。

  1. json_string = file.read()

在这个with语句的块中,我们使用read()方法读取文件的内容,并将其存储在名为json_string
的变量中。这样,我们可以在后续的代码中处理这个字符串,例如使用json.loads()将其转换为Python字典。

with语句的一个重要特性是,在块结束时,它会自动关闭文件。这意味着您不需要显式地调用file.close()
方法。当处理文件时,这可以确保文件被正确关闭,并减少资源泄漏的风险。

python中 with的用法一定要跟 as 结合在一起吗, 顺便也说下 as 的用法吧

with语句在Python中用于设置运行时上下文。它通常与as关键字一起使用,但并不总是必须这样。当使用with
语句时,通常与实现了上下文管理协议(即具有__enter__()__exit__()方法)的对象一起使用。with
语句确保在块结束时调用__exit__()方法,从而实现自动资源管理。

as关键字在with语句中的作用是为返回的上下文对象分配一个变量名,使您能够在with块中引用它。这在处理文件或数据库连接等资源时非常有用。

让我们通过一个简单的示例来说明withas的用法:


with open('example.txt', 'r') as file:  
    content = file.read()    
    print(content)

在此示例中,with语句用于打开名为example.txt的文件。open()函数返回一个文件对象,我们使用as
关键字为该对象分配了一个变量名file。在with块中,我们可以使用这个变量名来调用文件对象的方法,例如read()。当with
块结束时,file对象的__exit__()方法将被自动调用,从而关闭文件。

虽然withas通常一起使用,但您可以在不使用as的情况下使用with语句。在这种情况下,您将无法在with
块中引用上下文对象。以下是一个不使用as关键字的示例:


class Context:  
    def __enter__(self):        
        print("Entering the context")            
    def __exit__(self, exc_type, exc_value, traceback):  
        print("Exiting the context")  
with Context():  
    print("Inside the context")

在这个例子中,我们创建了一个简单的上下文管理器类Context,它包含__enter__()__exit__()方法。当我们使用with
语句时,我们不使用as关键字。因此,在with块中,我们无法引用Context对象。在这种情况下,with
仅确保在块结束时调用__exit__()方法。

总之,withas关键字通常一起使用,以便在with块中引用上下文对象。然而,as
关键字并不是必需的,您可以选择不使用它,但在这种情况下,您将无法在with块中引用上下文对象。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值