Removing Elements from Json Based on a Condition in C#

Removing elements from JSON based on a condition in C#

I've been attempting to compress this into a nicer LINQ statement for the last 10 minutes or so, but the fact that the list of known Ids is inherently changing how each element is evaluated means that I'm probably not going to get that to happen.

        var jObj = (JObject)JsonConvert.DeserializeObject(json);
var docsToRemove = new List<JToken>();
foreach (var doc in jObj["response"]["docs"])
{
var id = (string)doc["id"];
if (knownIds.Contains(id))
{
docsToRemove.Add(doc);
}
else
{
knownIds.Add(id);
}
}
foreach (var doc in docsToRemove)
doc.Remove();

This seems to work well with the crappy little console app I spun up to test, but my testing was limited to the sample data above so if there's any problems go ahead and leave a comment so I can fix them.

For what it's worth, this will basically run in linear time with respect to how many elements you feed it, which is likely all the more algorithmic performance you're going to get without getting hilarious with this problem. Spinning each page of ~100 records off into its own task using the Task Parallel Library invoking a worker that will handle its own little page and returned the cleaned JSON string comes to mind. That would certainly make this faster if you ran it on a multi-cored machine, and I'd be happy to provide some code to get you started on that, but it's also a huge overengineering for the scope of the problem as it's presented.

How to remove an item from a JSON string by value

You have a couple of options here since JArray does not have a RemoveAll(Predicate<JToken> match) method.

Firstly, you can use SelectTokens() to find all JArray items for which value == 2 and then remove them as follows:

var array = JArray.Parse(jsonString);

array.SelectTokens("[?(@.value == '2')]")
.ToList()
.ForEach(i => i.Remove());

The expression [?(@.value == '2')] is a JSONPath query; for details and documentation see # JSONPath - XPath for JSON and Querying JSON with complex JSON Path.

Note that this may have quadratic performance in the number of items to be removed, and so might be unacceptably slow if you are removing a large number of items.

Secondly, you can grab JTokenExtensions.RemoveAll(this JArray array, Predicate<JToken> match) from this answer to JArray - How to remove elements that are not contained in another list -fastest/best performance way:

public static partial class JTokenExtensions
{
/// <summary>
/// Removes all the elements that match the conditions defined by the specified predicate.
/// </summary>
public static void RemoveAll(this JArray array, Predicate<JToken> match)
{
if (array == null || match == null)
throw new ArgumentNullException();
array.ReplaceAll(array.Where(i => !match(i)).ToList());
}
}

Then remove your desired items as follows:

array.RemoveAll(i => (string)i["value"] == "2");

This will have linear performance in the number of items to be removed.

Demo fiddle here.

Delete JSON Data inside Property based on ID in C#

There is no need for creating deleteObject like you are doing, you are very close to solution.You can simply find your object like this and remove.

var companyToDeleted = experiencesArrary.Where(obj => obj["companyid"].Value<int>() == companyId).ToList();

foreach (var item in companyToDeleted)
{
experiencesArrary.Remove(item);
}

Update

var companyToDeleted = experiencesArrary.FirstOrDefault(obj => obj["companyid"].Value<int>() == companyId);

experiencesArrary.Remove(companyToDeleted);

How to remove set of Json Object based on condition in C#?

You can use deserialize the string into objects. Then use Linq to select the wanted items and then use Json.NET again to get the JSON string.

    public class Item
{
public string applicationName {get; set;}
public string machineName {get;set;}
public string OrderNumber {get; set;}
}

var items = JsonConvert.DeserializeObject<List<Item>>(JsonString);

var newJsonString = JsonConvert.SerializeObject(items.Where(i => i.OrderNumber != "D46364636"));

Remove Json Object in Json Array in c#

Among with the answer of Thierry Prost

namespace Testedouble
{
class Program
{
static void Main(string[] args)
{
var jsonString = @"{
'Type': 'Name',
'parameters': [
{
'A': {
'type': 'string',
'defaultValue': 'key'
},
'B': {
'type': 'string',
'defaultValue': 'key'
},
'C': {
'type': 'string',
'defaultValue': 'key'
},
'D': {
'type': 'string',
'defaultValue': 'autogenerated'
},
'E': {
'type': 'string',
'defaultValue': 'autogenerated'
},
'F': {
'type': 'dropdown',
'dropDownItems': [
'true',
'false'
],
'defaultValue': 'false'
}
}
]
}";

var values = JsonConvert.DeserializeObject<Foo>(jsonString);
foreach (var key in new string[] { "A", "B", "C" })
{
foreach (var item in values.parameters)
{
item.Remove(key);
}

}
Console.WriteLine(JsonConvert.SerializeObject(values));


}

public class Foo
{
public string Type { get; set; }
public List<Dictionary<string, object>> Parameters { get; set; }
}
}
}

Remove specific properties from JSON object

You can parse the string first:

var temp =  JArray.Parse(json);
temp.Descendants()
.OfType<JProperty>()
.Where(attr => attr.Name.StartsWith("_umb_"))
.ToList() // you should call ToList because you're about to changing the result, which is not possible if it is IEnumerable
.ForEach(attr => attr.Remove()); // removing unwanted attributes
json = temp.ToString(); // backing result to json

UPDATE OR:

result.Properties()
.Where(attr => attr.Name.StartsWith("_umb_"))
.ToList()
.ForEach(attr => attr.Remove());

UPDATE #2

You can specify more conditions in where clause:

.Where(attr => attr.Name.StartsWith("_umb_") && some_other_condition)

OR

.Where(attr => attr.Name.StartsWith("_umb_") || some_other_condition)

Or whatever you need.

Remove an element from JsonResult in C#

You can create a new object, excluding the properties you don't want sent in the result...

var anonymousObj = new {
myObject.PropertyToExpose,
myObject.Otherthings
};
JsonResult result = Json(anonymousObj, JsonRequestBehavior.AllowGet);

Another options could be to convert the object to a Newtonsoft.Json.Linq.JObject and remove the property using JObject.Remove Method (String)

var jObject = JObject.FromObject(myObject);
jObject.Remove("PropertyToNOTExpose");
var json = jObject.ToString(); // Returns the indented JSON for this token.
var result = Content(json,"application/json");

How to validate and remove nested nodes of JSON Object

I will also suggest using model class, but for your case this should work

 JObject jsonObject = JObject.Parse(json);
JToken jToken = JToken.Parse(json);

var result = jToken["movieList"].SelectMany(x => x["showTimes"]).ToList();

foreach (var item in result)
{
var times = item.SelectTokens("time").Values().ToList();
if (!times.Where(x => x.ToString().Trim() == "18:00").Any())
{
item.Remove();
}
}

var output = jToken.ToString(Formatting.Indented);
Console.WriteLine(output);

output

{
"movieList": [
{
"movieID": 1,
"title": "TITLE 1",
"showTimes": [
{
"date": "xx",
"time": [
"18:00"
]
},
{
"date": "xx",
"time": [
"11:00",
"15:00",
"18:00"
]
}
]
}
]
}


Related Topics



Leave a reply



Submit