C#如何从动态JSON文件中提取父级键与对应title字段值
实现方案
核心逻辑
你只需要按以下步骤处理即可:
- 读取用户自主选择的JSON文件,解析为对应编程语言的字典/对象结构
- 遍历顶层字典的所有键值对,顶层键即为需要提取的Tag
- 仅判断当前条目是否存在
title字段,存在则按要求格式输出Tag和title值,自动忽略description等其他非必要字段
代码示例
Python 实现(桌面应用场景)
import json import tkinter as tk from tkinter import filedialog # 初始化隐藏tkinter主窗口 root = tk.Tk() root.withdraw() # 弹出文件选择框,限制仅可选JSON文件 file_path = filedialog.askopenfilename(filetypes=[("JSON格式文件", "*.json")]) if file_path: # 加载解析JSON内容 with open(file_path, 'r', encoding='utf-8') as f: json_data = json.load(f) # 遍历提取所需字段 for tag, item in json_data.items(): if 'title' in item: print(f'Tag: "{tag}"') print(f'Name: "{item["title"]}"')
JavaScript 实现(Web应用场景)
对应的HTML输入框:
<input type="file" id="json-upload" accept="application/json">
JS逻辑:
// 绑定文件选择输入框的change事件 document.getElementById('json-upload').addEventListener('change', async (event) => { const selectedFile = event.target.files[0] if (!selectedFile || selectedFile.type !== 'application/json') return // 读取解析JSON内容 const fileContent = await selectedFile.text() const jsonData = JSON.parse(fileContent) // 遍历提取所需字段 Object.entries(jsonData).forEach(([tag, item]) => { if (item.title) { console.log(`Tag: "${tag}"`) console.log(`Name: "${item.title}"`) } }) })
内容的提问来源于stack exchange,提问作者Redstone145
相关产品推荐
相关产品推荐

