user3741174
user3741174

Reputation: 33

Checking for key name in nested json

I need to check if a keyname exists in a json file, but I can't figure out how to do it.

Json file:

{
  "value": [
    {
      "from": 1430611201000,
      "to": 1430697600000,
      "ref": "2015-05-03",
      "value": "8.4",
      "quality": "Y"
    }
  ],
  "updated": 1430726400000,
  "parameter": {
    "key": "2",
    "name": "Lufttemperatur",
    "summary": "medelvärde 1 dygn, 1 gång/dygn, kl 00",
    "unit": "degree celsius"
  },

I think this is the closest I got, but it will always be false (even when I search for an existing key): content is a JObject.

var searchDate = content.Properties().Select(p => p.Value).Children().Any(p=>p.Contains("quality"));

EDIT: I've changed the key name to "quality", for clarifing the question. I will also use another json file that contains the key "date" instead of "from" and "to". To seperate the files I want to know is "date" exists or not.

Upvotes: 3

Views: 2033

Answers (2)

har07
har07

Reputation: 89285

If the property to be checked is always belong to an item in the value property, then you can do this way :

var isQualityExists = 
            content["value"].Any(v => ((JObject)v).Properties()
                                                  .Any(p => p.Name.Contains("quality"))
                                );

Otherwise, you may want to create a function that recursively check for a specific property name existence all over the JObject.

Upvotes: 4

Somesh Chadda
Somesh Chadda

Reputation: 19

date does not exist in json. Thats why you get false as mentioned in one of the comments. If you want to search for key:"to"

if("to" in json_object) 
{
//your logic goes here
}

Upvotes: 0

Related Questions