python json转xml
前景提要
17:55,你正准备关机,老板在群里@你:“把客户给的 test-input.json
转成 xml,今晚接口联调要用。”
你打开文件,瞬间头大:嵌套的对象、数组、布尔值混成一锅粥。手敲 <tag>
?估计得加班到凌晨。
你把同事刚发你的 json_to_xml.py
往命令行一扔——
python json_to_xml.py
3 秒后,test-output.xml
静静躺在桌面,标签层级分明,连 <?xml version="1.0"?>
都写好了。
这把“瑞士军刀”从此常驻你的 u 盘。
代码解析 1
通俗解释
就像把一封英文信先翻译成中文再读,这一步让 python 能把 json 内容当积木玩。
关键代码
with open("test-input.json", "r") as json_file: json_data = json.load(json_file) # 把 json 字符串变成 python 字典或列表
代码解析 2
通俗解释
json 像俄罗斯套娃,大盒子里还有小盒子。脚本一层层拆开:遇到盒子(对象/数组)就继续拆,遇到糖果(字符串/数字)就贴标签。
关键代码
def json_to_xml(json_obj, line_padding=""): result_list = [] if isinstance(json_obj, dict): for key, value in json_obj.items(): result_list.append(f"{line_padding}<{key}>") result_list.append(json_to_xml(value, line_padding + " ")) result_list.append(f"{line_padding}</{key}>") elif isinstance(json_obj, list): for element in json_obj: result_list.append(json_to_xml(element, line_padding)) else: result_list.append(f"{line_padding}{json_obj}") return "\n".join(result_list)
代码解析 3
通俗解释
拆到最底层时,脚本自动把键名变成标签名,把值放进标签中间,同时用两个空格缩进,让 xml 像楼梯一样好看。
关键代码
# 示例输出片段 """ <person> <name>alice</name> <age>30</age> </person> """
代码解析 4
通俗解释
就像把整理好的笔记放进文件夹,这一步把字符串一次性写进文件,顺手加上 xml 文件头。
关键代码
xml_data_with_header = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + xml_data with open("test-output.xml", "w") as file: file.write(xml_data_with_header)
扩展点子
1. 批量处理整个文件夹
给脚本加一个循环,让它一次吃下一整碗 json。
import glob for json_path in glob.glob("*.json"): with open(json_path, "r") as f: data = json.load(f) xml_str = json_to_xml(data) save_xml_file(xml_str, json_path.replace(".json", ".xml"))
2. 30 秒套个图形界面
用 tkinter
做一个小窗口,拖文件就能转。
import tkinter as tk from tkinter import filedialog root = tk.tk() root.withdraw() # 只弹出文件选择框 input_path = filedialog.askopenfilename(title="选 json") with open(input_path, "r") as f: xml = json_to_xml(json.load(f)) save_xml_file(xml, input_path.replace(".json", ".xml"))
总结
你刚体验了一把“零门槛”自动化:把任何 json 文件扔给脚本,3 秒就能收获排版漂亮的 xml。它不需要安装额外库,只用系统自带 python;加上两条简单扩展,还能批量、还能点点鼠标。下次再有人甩来配置,你就笑眯眯地双击脚本——下班前就能回家追剧。
python json转markdown
周五 18:00,你正准备关机,老板甩来一个 200 行的 config.json:“下班前把这份配置整理成文档发我。”
你打开文件,瞬间眼花:嵌套的对象、数组、布尔值混成一团。手敲 markdown?估计得加班到半夜。
这时,你把今天刚拿到的小脚本 script.py 往命令行一扔——
python script.py -i config.json -o config.md
3 秒后,config.md 静静躺在桌面:标题、缩进、代码块全排好,老板直夸“专业”。
这把“瑞士军刀”从此常驻你的工具箱。
代码解析 1
通俗解释
就像把一封英文信先翻译成中文再读,这一步让 python 能“听懂” json 的内容。
关键代码
def load_json(file): try: with open(file, 'r') as f: data = f.read() return json.loads(data) # 把 json 字符串变成 python 字典或列表 except: print("[error] 文件必须是合法的 json")
代码解析 2
通俗解释
json 像俄罗斯套娃,大盒子里还有小盒子。脚本一层层拆开,遇到盒子(对象/数组)就继续拆,遇到糖果(字符串/数字)就贴标签。
关键代码
def parse_json(json_block, depth, options): if isinstance(json_block, dict): parse_dict(json_block, depth, options) if isinstance(json_block, list): parse_list(json_block, depth, options)
代码解析 3
通俗解释
拆到最后,给每个“糖果”写上名字和味道:age: 18。脚本自动在前面加 - 和反引号,让 markdown 格式一步到位。
关键代码
def add_value(key, value, depth): chain = tab * (bool(depth - 1)) + list_tag + \ str(key) + ": " + inline_code + str(value) + inline_code + "\n" global markdown markdown += chain
代码解析 4
通俗解释
就像把整理好的笔记放进文件夹,这一步把生成的 markdown 字符串一次性写进指定文件,完事收工。
关键代码
def write_out(markdown, output_file): with open(output_file, 'w+') as f: f.write(markdown)
扩展点子
1. 批量处理整个文件夹
给脚本加一个 -b 参数,让它一次吃下一整碗 json。
# 在 main() 里加几行 import glob if args.batch: for json_path in glob.glob('*.json'): convert(json_path, json_path[:-4] + 'md', options)
2. 30 秒套个图形界面
用 tkinter 做一个小窗口,拖文件就能转。
import tkinter as tk from tkinter import filedialog root = tk.tk() root.withdraw() # 只弹出文件选择框 input_path = filedialog.askopenfilename(title="选 json") convert(input_path, input_path[:-4] + 'md', {'ignore': '', 'keep': ''})
总结
你刚体验了一把“零门槛”自动化:把任何 json 文件扔给脚本,3 秒就能收获排版漂亮的 markdown。它不需要安装额外库,只用系统自带 python;加上两条简单扩展,还能批量、还能点点鼠标。下次再有人甩来配置,你就笑眯眯地双击脚本——下班前就能回家追番。
到此这篇关于python实现将json转换为xml与markdown的文章就介绍到这了,更多相关python json格式转换内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论