如何使用C#从json文件中删除空的token/item?

cqoc49vn  于 2023-02-26  发布在  C#
关注(0)|答案(1)|浏览(179)

如何删除json文件中所有值为'N/A''-'''的键,例如:

{
    "name": {
        "first": "Robert",
        "middle": "",
        "last": "Smith"
    },
    "age": 25,
    "DOB": "-",
    "hobbies": [
        "running",
        "coding",
        "-"
    ],
    "education": {
        "highschool": "N/A",
        "college": "Yale"
    }
}

在这种情况下,需要删除middlehighschool
我试着用这个:

var json = JObject.Parse(jsonString);

json.SelectTokens("@==''").FirstOrDefault().Remove();
y0u0uwnf

y0u0uwnf1#

您可以尝试以下代码:

string jsonString = @"
    {
        ""name"": {
            ""first"": ""Robert"",
            ""middle"": """",
            ""last"": ""Smith""
        },
        ""age"": 25,
        ""DOB"": ""-"",
        ""hobbies"": [
            ""running"",
            ""coding"",
            ""-""
        ],
        ""education"": {
            ""highschool"": ""N/A"",
            ""college"": ""Yale""
        }
    }";
  • 将JSON字符串解析为JObject:
JObject json = JObject.Parse(jsonString);
  • 获取值为“N/A”、“-"或空字符串的所有属性:
var propertiesToRemove = json.Descendants()
                                .OfType<JProperty>()
                                .Where(p => p.Value.Type == JTokenType.String && 
                                  (string)p.Value == "N/A" || (string)p.Value == "-" || (string)p.Value == "").ToList();
  • 删除所选属性:
foreach (var property in propertiesToRemove)
         {
             property.Remove();
         }

相关问题