There is a small JSON file (~ 400 lines), which has a similar structure:

 { "Items": [ { "type": "Тип 1", "Ключ1": "Значение 1", "Ключ2": "Значение 2" }, { "type": "Тип 2", "Ключ3": "Значение 3", "Ключ4": "Значение 4" } ] } 

The file is apparently divided into sections, where the first value is always type - this value indicates the name of the category. Also in each category there is a value (here I have designated as a key) - it is unique.

The question is, how can I search the entire file with only the Ключ - get its Значение and the current "category", which is in type ?

At the moment I load the entire file line by line and in the resulting array I search for a string that has the necessary key. Next, I deserialize this value and pull out the value. This option works quite well, but I can't get type , and this option itself looks like a “crutch”.


For clarity, an example:

We have for example "Klyuch3" - we do a search - at the output we get the "Value 3" and "Type 2".

  • 2
    You need to create a class and deserialize json into a List. There it is already possible with the help of Linq or simply by searching through the necessary lines. - koshe
  • one
    I support the previous speaker. JSON is a data serialization format. Deserialize and look for what you need in the object structure. - VladD

1 answer 1

Given your JSON data structure and if you don’t want to deserialize into an object view, your task can be solved this way, since Json.Net supports Linq :

 JObject json = JObject.Parse(jsonText); var result = json["Items"] .Where(s => s["Ключ3"] != null) .Select(s => new { Value = s["Ключ3"].ToString(), Type = s["type"]?.ToString() }).ToList(); 
  • The first question mark can be removed in theory, you are checking that s["Ключ3"] != null . - VladD
  • @VladD thanks, true comment. - sp7
  • @ sp7 Thanks, good decision. - EvgeniyZ
  • @EvgeniyZ, please. - sp7