gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:50:33 26 4
gpt4 key购买 nike

概括:

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

我的 denullifier 代码:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com