Home > Software design >  How to delete a property in a JArray?
How to delete a property in a JArray?

Time:05-04

I have a JArray as below, the file property contained a base64 string so it's a big size, how to delete it?

{ 
  "files": [
    {
      "filename": "892a3a3bb7814d67995d4059b278c581.png",
      "real_filename": "Logo - Trimmed.png",
      "filesize": 42198,
      "filetype": "image/png",
      "file": "xxxx"
    },
    {
      "filename": "22a3a3bb7814d67995d4059b278c581.png",
      "real_filename": "Logo - Trimmed2.png",
      "filesize": 42198,
      "filetype": "image/png",
      "file": "xxxx"
    }
  ] 
}

I have tried below, but it threw me an exception:

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

for (int _i = 0; _i < _ja_files.Count; _i  ) 
{
     _ja_files[_i]["file"].Remove();
}

CodePudding user response:

Iterate the JObject in JArray and with JObject.Remove() to remove the property.

var jObj = JObject.Parse(jsonStr);
        
foreach (JObject obj in jObj["files"] as JArray)
{
    obj.Remove("file");
}

Sample program

  • Related