c# - 如果要删除某些元素,如何迭代 JObject?

标签 c# json collections json.net

摘要:

通过美国教育部 API,我计划创建一份大学列表及其计算机科学毕业生的中位工资。但是,许多学校都有空值,尝试删除空值会破坏代码,因为在枚举集合时无法修改集合。

我的取消器代码:

static JObject DeNullifier(JObject inputJson)
{
    //Each school in the results[] section
    foreach(var school in inputJson["results"])
    {
        //Each degree in the cip_4_digit section
        foreach(var degree in school["latest.programs.cip_4_digit"])
        {
            if(string.IsNullOrEmpty(degree["earnings.median_earnings"].Value<string>()))
            {
                degree.Remove();
            }
        }
    }
    return inputJson;
}

JSON 缩短版本:

{
    "metadata": 
    {
        "total": 1444,
        "page": 14,
        "per_page": 100
    },

    "results": 
    [
        {
            "school.name": "Georgia College & State University",
            "latest.programs.cip_4_digit": 
            [
                {
                  "earnings.median_earnings": 53200,
                  "title": "Computer Science.",
                  "code": "1107"
                }
            ]
        },
        {
            "school.name": "Georgia Southern University",
            "latest.programs.cip_4_digit": 
            [
                {
                  "earnings.median_earnings": null,
                  "title": "Computer Science.",
                  "code": "1107"
                }
            ]
        }
    ]
}

Newtonsoft JSON.NET 类引用:

https://www.newtonsoft.com/json/help/html/Methods_T_Newtonsoft_Json_Linq_JObject.htm

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JToken.htm

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JProperty.htm

最佳答案

您可以将要删除的节点添加到不同的集合中,然后将其删除。例如,

static JObject DeNullifier(JObject inputJson)
{
    var nodesToRemove = new List<JToken>();
    //Each school in the results[] section
    foreach(var school in inputJson["results"])
    {
        //Each degree in the cip_4_digit section
        foreach(var degree in school["latest.programs.cip_4_digit"])
        {
            if(string.IsNullOrEmpty(degree["earnings.median_earnings"].Value<string>()))
            {
                nodesToRemove.Add(degree);
            }
        }
    }

    foreach(var node in nodesToRemove)
    {
        node.Remove();
    }
    return inputJson;
}

关于c# - 如果要删除某些元素,如何迭代 JObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59494431/

相关文章:

C# Jupyter 笔记本

c# - 将 Newtonsoft 代码转换为使用 Newtonsoft.Json.Linq.JObject 的 System.Text.Json

javascript - 在 Rails 中创建 JSON 对象,然后使用 jQuery/Ajax 从操作中获取 JSON 的正确方法是什么?

python - 如何使用 python 格式化具有多个相同键的 JSON?

java - “释放”Java 列表中的迭代器

c# - C# 3 中具有接口(interface)继承(co(ntra)-variance?)的泛型类型推断

c# - 多个独立数据库事务的并发问题?

c# - 如何等待第 2 个 : a process and an EventWaitHandle

ios - 无法从服务器 api 解析 JSON

java - 就地过滤 Java 列表,无需外部库