Home > other >  List keys inside a child for JSON
List keys inside a child for JSON

Time:06-30

I have a JSON file with the following data:

{ 
  "users": {
    "xyz ": {
      "Name": "abc ",
    },
    "x ": {
      "Name": "xy ",
    },
    "abc": {
      "Name": "ijk",
    },
  }
}

I deserialize the JSON file in C# to a dynamic data type by following code:

dynamic keys = JsonConvert.DeserializeObject(File.ReadAllText(path));

Now I wanna retrieve the name of keys present inside the child of users.

I want the following output:

xyz
x
abc

How can I list the name of the keys?

CodePudding user response:

  1. Read JSON as JObject.
  2. Get users JObject from 1.
  3. Convert JObject to Dictionary<string, object> and get Keys from the dictionary.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;

JObject obj = JObject.Parse(File.ReadAllText(path));
JObject users = (JObject)obj["users"];
List<string> keys = users.ToObject<Dictionary<string, object>>()
    .Keys
    .ToList();

Sample .NET Fiddle

Note that the keys contain space in your attached JSON.

CodePudding user response:

you don't need to deserialize to dictionary, to parse is enough

List<string> keys= ((JObject) JObject.Parse(File.ReadAllText(path))["users"])
.Properties().Select(u =>  u.Name).ToList();

CodePudding user response:

Isn't this all you need?

List<string> list = new List<string>();
foreach(var user in keys.users)
{
  list.Add(user.toString());
}
            
  • Related