Kanishka
Kanishka

Reputation: 363

querying json array using property

I have some JSON like this :

[{
    "Headers": ["Building ID",
    "Building",
    "Active",
    "Last Updated Date"],
    "ID": "Table_1890",
    "Rows": [["1",
    "2 Chifley Tower, Sydney",
    "True",
    ""],
    ["5",
    "60 Martin Place, Sydney",
    "True",
    ""],
    ["11",
    "275 Kent Street, Sydney",
    "True",
    ""],
    ["16",
    "360 Collins Street, Melbourne",
    "False",
    ""]]
},
{
    "Headers": ["FloorID",
    "Floor",
    "Active",
    "Last Updated Date"],
    "ID": "Table_1890",
    "Rows": [["1",
    "2 Chifley Tower, Sydney",
    "True",
    ""],
    ["5",
    "60 Martin Place, Sydney",
    "True",
    ""],
    ["11",
    "275 Kent Street, Sydney",
    "True",
    ""],
    ["16",
    "360 Collins Street, Melbourne",
    "False",
    ""]]
}]

I want to query specific JSON array using Headers property. for example I want to get the array where "Headers": ["Building ID","Building","Active","Last Updated Date"]. So this should return me the first array which includes the headers, ID, rows. I really appreciate any help as to how can I achieve this. I am using Newtonsoft and I am deserializing this array.

Currently I do this. This gives errors:

string json = File.ReadAllText(fileSavePath+"\\1240.txt");
JArray ja = JArray.Parse(json); 
JObject match = ja.Values<JObject>()
    .Where(m => m["Headers"].Value<string>() == "[\"Building ID\",\"Building\",\"Active\",\"Last Updated Date\"]")
    .FirstOrDefault();

Upvotes: 0

Views: 41

Answers (1)

Kien Chu
Kien Chu

Reputation: 4895

Note: compare string like your solution is not safe, you might need to remove white space and trim it. I think you need to find more elegant way to compare the header value.

Below is working code:

JArray objects = JsonConvert.DeserializeObject<JArray>(json);

var compare = @"[
""BuildingID"",
""Building"",
""Active"",
""LastUpdatedDate""
]";

JObject match = objects.Children<JObject>().FirstOrDefault(o => o["Headers"] != null && o["Headers"].ToString().Replace(" ", "") == compare);

Upvotes: 1

Related Questions