如何在C#中删除JSON文件中含Empty文本的多段属性
批量清理JSON文件中Empty属性的C#实现
以下是完善后的完整代码,实现了删除value为"Empty"的属性、重新序列化并覆盖原文件的功能:
using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.Text.Json; using System.Text.Encodings.Web; internal class Program { private static void Main(string[] args) { var jsonPath = @"/Users/jasonnienaber/Desktop/nft/cef/official/fatJSONselfFIX/test/test2"; var jsonFiles = Directory.GetFiles(jsonPath, "*.json").OrderBy(f => f); string emptyValue = "Empty"; // 序列化配置,保持JSON格式化输出,和原文件格式一致 var serializeOptions = new JsonSerializerOptions { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 避免特殊字符不必要转义 }; foreach (var jsonFile in jsonFiles) { try { var jsonContent = File.ReadAllText(jsonFile); var sample = JsonSerializer.Deserialize<Sample>(jsonContent); // 过滤掉value为Empty的属性,处理attributes为null的边界情况 if (sample.attributes != null) { sample.attributes = sample.attributes .Where(attr => !string.Equals(attr.value, emptyValue, StringComparison.OrdinalIgnoreCase)) .ToList(); } // 重新序列化为JSON var updatedJson = JsonSerializer.Serialize(sample, serializeOptions); // 覆盖原文件(建议先备份文件再执行批量操作) File.WriteAllText(jsonFile, updatedJson); Console.WriteLine($"处理完成:{jsonFile}"); } catch (Exception ex) { Console.WriteLine($"处理文件失败 {jsonFile}:{ex.Message}"); } } Console.WriteLine("所有文件处理完成"); } public class Attribute { public string trait_type { get; set; } public string value { get; set; } } public class Sample { public string image { get; set; } public string name { get; set; } public string description { get; set; } public string external_url { get; set; } public List<Attribute> attributes { get; set; } public string compiler { get; set; } } }
关键改动说明
- 补充必要命名空间:引入
System.Linq用于列表过滤,原代码中未用到的System.Web可移除 - 属性过滤逻辑:用LINQ的
Where方法筛选出非Empty的属性,加入StringComparison.OrdinalIgnoreCase兼容大小写差异;同时判断attributes是否为null,避免空引用异常 - 序列化配置:通过
JsonSerializerOptions开启WriteIndented保证输出JSON的格式化结构,和原文件一致;UnsafeRelaxedJsonEscaping避免URL等特殊字符被不必要转义 - 错误处理:添加
try-catch块捕获单个文件的处理异常,防止单个文件出错导致整个批量任务终止 - 文件写入:直接覆盖原文件,正式批量处理前建议先备份测试目录文件,防止数据丢失
注意事项
- 先在少量测试文件上验证功能,确认无误后再处理10000个文件
- 若需保留原文件,可在写入前添加备份逻辑:
File.Copy(jsonFile, Path.Combine(备份目录路径, Path.GetFileName(jsonFile))); - 若JSON文件编码非UTF-8,需在
File.ReadAllText和File.WriteAllText中指定对应编码参数
内容的提问来源于stack exchange,提问作者Jason Nathan
相关产品推荐
相关产品推荐

