John Abel
John Abel

Reputation: 281

Select and remove a nested key value from JObject

I have a JObject for which I would like to check if a certain key value pair exists and if so get the value from the key and then remove the key.

JObject-props

{
  "name": "Red Game",
  "id": "0060a00000alKw3AAE",
  "statecode": 0,
  "StudioId": {
    "pfstudioid": "B20996D68598FF7F"
  },
  "statuscode": 1,
  "lastapicall": "2018-10-11T00:00:00Z"
}

in my code I have:

if (props.ContainsKey("StudioId.pfstudioid"))
{
    string value= props.GetValue("StudioId.pfstudioid")                      
    props.Remove("StudioId.pfstudioid");
}

But it doesn't find the that they key exists in the JObject and skips the if condition block. How do I write this correctly?

Upvotes: 4

Views: 3863

Answers (1)

Blue
Blue

Reputation: 22921

The problem isn't your .ContainsKey method, it's the props.Remove(). You cannot use dot notation, to remove a subkey. You can delete this key this way:

props.Value<JObject>("StudioId").Remove("pfstudioid");

See my .net fiddle here: https://dotnetfiddle.net/8mVEaa

Upvotes: 10

Related Questions