Delete elements from a JSON

孤者浪人 提交于 2021-02-08 09:35:29

问题


I have this JSON like this:

   {
"flight" : [ 
   {    
            "arv" : { 
        "@aptCode" : "JFK"
        },
            "legs" : { "@count" : "1",
                "leg" : { "@arvDayIndicator" : "0",
                    "@wetLease" : "False",

                    "mealCodes" : "M M M M M M M M M M M M M M M M M M M M M M",
                    "operation" : { "@acftOwner" : "",
                        "@operatedBy" : ""
                      }                        
                  }
              }

          },
      { 
            "arv" : { "@aptCode" : "LHR" },
            "legs" : { "@count" : "2",
                "leg" : { "@arvDayIndicator" : "0",
                    "@wetLease" : "False",

                    "mealCodes" : "M M M M M M M M M M M M M f M M f M M M f M",
                    "operation" : { "@acftOwner" : "",
                        "@operatedBy" : ""
                      }                       
                  }
              }

          }]}

How can remove the inner values like :

"@wetLease","mealCodes" or "@operatedBy"

I try with:

jSon.SelectToken(@"flight[0].arv").Remove();

for first instance but give me the next error:

Cannot add or remove items from Newtonsoft.Json.Linq.JProperty


回答1:


var names = new List<string>(){"@wetLease","mealCodes" , "@operatedBy"};

var jObj = JObject.Parse(json);

jObj.Descendants().OfType<JProperty>()
    .Where(p=>names.Contains(p.Name))
    .ToList()
    .ForEach(p=>p.Remove());

var newjson = jObj.ToString();


来源:https://stackoverflow.com/questions/25510270/delete-elements-from-a-json

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!