You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于指定字段过滤JArray并保留唯一元素?

按指定字段集合对JArray去重并保存为JSON

实现思路

核心逻辑是基于指定字段组合生成唯一标识,用哈希集合记录已出现的标识,遍历JArray时仅保留首次出现的对应元素,确保最终结果中指定字段的组合唯一。

代码实现

以下基于Newtonsoft.Json库(处理JArray的常用工具)编写完整解决方案:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

class JsonDeduplicator
{
    static void Main(string[] args)
    {
        // 读取原始JSON文件
        string inputPath = "your_input.json";
        JArray originalArray = JArray.Parse(File.ReadAllText(inputPath));

        // 定义要用于去重的字段集合,可按需修改
        var deduplicateFields = new List<string> { "name", "pos" };

        var seenCombinationKeys = new HashSet<string>();
        var deduplicatedArray = new JArray();

        foreach (JObject item in originalArray)
        {
            // 生成当前元素的唯一标识:按字段顺序拼接值(用分隔符避免值拼接冲突)
            string combinationKey = string.Join("||", deduplicateFields.Select(f => item[f]?.ToString() ?? string.Empty));
            
            if (!seenCombinationKeys.Contains(combinationKey))
            {
                seenCombinationKeys.Add(combinationKey);
                deduplicatedArray.Add(item);
            }
        }

        // 将去重后的结果写入新JSON文件
        File.WriteAllText("your_output.json", deduplicatedArray.ToString(Formatting.Indented));
    }
}

关键细节说明

  • 性能适配:哈希集合的查找操作是O(1)时间复杂度,3000个元素的处理完全无压力
  • 空值兼容:用?? string.Empty处理字段为null的情况,避免空引用异常
  • 灵活切换字段:修改deduplicateFields列表即可适配不同去重规则:
    • 示例1规则:var deduplicateFields = new List<string> { "name" };
    • 示例2规则:var deduplicateFields = new List<string> { "name", "pos" };
  • 保留首次元素:遍历过程中仅保留首次出现的字段组合元素,与示例预期结果一致

内容的提问来源于stack exchange,提问作者Eugene

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:03:17