如何使用Python将指定字段转换为合规JSON格式并写入文件
直接转换JSON的实现方案
原数据的tags字段本身是列表嵌套单键字典的结构,JSON原生支持该结构,不需要合并内部字典,不会出现同键冲突问题,因为每个单键字典都是数组内的独立对象,不存在同一父级下重复键的情况。
规范JSON格式示例
{ "url": "blewpass.com", "ssl": "yes", "tags": [ {"html": "hi"}, {"title": "My first page"}, {"h2": "My First Line"}, {"p": "Hey"}, {"h2": "My Second Line"} ] }
Python实现代码(转存为JSON文件)
import json # 原始数据定义 raw_data = { "url": "blewpass.com", "ssl": "yes", "tags": [ {"html":"hi"}, {"title":"My first page"}, {"h2":"My First Line"}, {"p":"Hey"}, {"h2":"My Second Line"} ] } # 写入文件,indent参数用于格式化输出,ensure_ascii避免特殊字符乱码 with open("page_info.json", "w", encoding="utf-8") as file: json.dump(raw_data, file, ensure_ascii=False, indent=2)
可选优化结构(提升检索效率)
如果后续需要按标签类型快速检索内容,可以调整tags为「标签类型对应内容数组」的结构,既不会出现同键冲突,也能提升管理效率,格式示例如下:
{ "url": "blewpass.com", "ssl": "yes", "tags": { "html": ["hi"], "title": ["My first page"], "h2": ["My First Line", "My Second Line"], "p": ["Hey"] } }
内容的提问来源于stack exchange,提问作者Rikky Bhai
相关产品推荐
相关产品推荐

