1

I have this JSON, and I want to delete "delta" section with all nested property. I already use JObject.Remove("delta") but I have this error:

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

JSON

{
  "state": {
    "desired": {
      "optionals": {
        "Variant": "XXXX",
        "Vehicle": {
          "COC00": "AAAA",
          "D0000": "BBBB",
          "D0600": "CCCC"
        }
      }
    },
    "delta": {
      "optionals": {
        "Variant": "XXXX",
        "Vehicle": {
          "COC00": "AAAA",
          "D0000": "BBBB",
          "D0600": "CCCC"
          "D2000": "DDDD",
        }
      }
    }
  },
  "timestamp": 1700154568
}
3
  • Does this answer your question? Remove Node From JSON dynamically in C# or this perhaps? JSON.NET how to remove nodes Commented Nov 16, 2023 at 17:25
  • The above solution is verbose but performant. If this is not a bottleneck you can just deserialize this json to the object with desired shape then serialize it to json. Commented Nov 16, 2023 at 17:31
  • I think you're calling Remove on the wrong object. The message says you are calling Remove on an instance of a JProperty. I would expect you are using a JToken as an interface, but probably you are calling stateProperty.Remove("delta"). But you would need to call something like stateProperty.Value.Remove("delta") (I'm not sure about the exact API) Commented Nov 16, 2023 at 17:39

1 Answer 1

2

Use selectToken and then remove the property.

    JObject jo = JObject.Parse(json);
    JObject header = (JObject)jo.SelectToken("state");
    header.Property("delta").Remove();
    json = jo.ToString();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.