Capitalizing the First Letter in All Keys of a JSON Object using C#

It took me some time to get this right, drawing from discussions on StackOverflow, but here is code that will capitalize the first letter of every key in a JSON object.

public static JObject Capitalize(JObject obj)
{
  JObject newObj = new JObject();
  foreach (var o in obj)
    {
      string key = o.Key;
      string newKey = char.ToUpper(key[0]) + key.Substring(1);
      JToken value = o.Value;
      if (value.HasValues)
      {
        try
        {
          JObject child = JObject.Parse(value.ToString());
          JObject newValue = Capitalize(child);
          value = newValue;
        }
        catch (Exception)
        {
        }
      }
      newObj[newKey] = value;
    }
  return newObj;
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.