Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select and remove a nested key value from JObject

Tags:

json

c#

json.net

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?

like image 932
John Abel Avatar asked Oct 22 '25 14:10

John Abel


1 Answers

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

like image 109
ugh StackExchange Avatar answered Oct 24 '25 04:10

ugh StackExchange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!