Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove particular attribute from JSON string using C#

Tags:

json

c#

I have JSON string as below

[{
        "attachments": [{ "comment": "communication", "comment_date_time": "2035826"} ], 
        "spent_hours": "4.00", 
        "description": ""       
    }, 
   {
        "attachments": [], 
        "spent_hours": "4.00", 
        "description": ""       
    }]

How can i remove the attachments attribute from the JSON string using C#. I am using JSON.net.

like image 871
Irappa Bisanakoppa Avatar asked May 28 '13 06:05

Irappa Bisanakoppa


People also ask

How do I delete a variable in JSON?

To remove JSON element, use the delete keyword in JavaScript.

How do you remove a key value pair from a JSON object?

JsonObject::remove() removes a key-value pair from the object pointed by the JsonObject . If the JsonObject is null, this function does nothing.


1 Answers

Using Linq

var jArr =  JArray.Parse(json);

jArr.Descendants().OfType<JProperty>()
                  .Where(p => p.Name == "attachments")
                  .ToList()
                  .ForEach(att=>att.Remove());

var newJson = jArr.ToString();

or using anonymous classes

var anon = new[] { new{spent_hours="", description=""} };
var newJson = JsonConvert.SerializeObject(
                         JsonConvert.DeserializeAnonymousType(json, anon));
like image 189
I4V Avatar answered Sep 19 '22 18:09

I4V