Given a Json, how do we get all the keys in it ? Just the keys. For example, Consider the Json below.
{ Person:['Jia Anu', 'Anu Viswan','Sreena Anu'], Details:[ { Name: 'Jia Anu', Age:3, }, { Name: 'Anu Viswan', Age:35, }, { Name: 'Sreena Anu', Age:34, } ], Address : 'Address here', State : 'Kerala', Country : 'India' }
Given the above Json, you would like to get all the keys. You might be later interested to show this as a Menu or Dropdown, that’s down to the requirements. But, how do we get the keys in first place ? May be a Linq One liner would be great ?
Person Details Details.Name Details.Age Address State Country
Of course, you do have the option to loop through the JTokens, but the easiest way out would be using Linq.
var data = JObject.Parse(jsonString); var result = data.Descendants() .OfType<JProperty>() .Select(f=>Regex.Replace(f.Path,@"\[[0-9]\]",string.Empty)) .Distinct();
The Regex involed is to ensure the arrays indices are removed and keys in arrays aren’t duplicated. The output of above Linq would give you collection of all keys in the Json as expected.