using Newtonsoft.Json.Linq;
using System.Collections.Generic;
public static void Main()
JObject o = JObject.Parse(@"{
'Name': 'Headlight Fluid',
foreach (JToken token in o.FindTokens("Name"))
if(!token.Path.Contains("Products"))
token.Rename("LongName");
Console.WriteLine(o.ToString());
public static class JsonExtensions
public static List<JToken> FindTokens(this JToken containerToken, string name)
List<JToken> matches = new List<JToken>();
FindTokens(containerToken, name, matches);
public static void Rename(this JToken token, string newName)
throw new ArgumentNullException("token", "Cannot rename a null token");
if (token.Type == JTokenType.Property)
if (token.Parent == null)
throw new InvalidOperationException("Cannot rename a property with no parent");
property = (JProperty)token;
if (token.Parent == null || token.Parent.Type != JTokenType.Property)
throw new InvalidOperationException("This token's parent is not a JProperty; cannot rename");
property = (JProperty)token.Parent;
var existingValue = property.Value;
var newProperty = new JProperty(newName, existingValue);
property.Replace(newProperty);
private static void FindTokens(JToken containerToken, string name, List<JToken> matches)
if (containerToken.Type == JTokenType.Object)
foreach (JProperty child in containerToken.Children<JProperty>())
matches.Add(child.Value);
FindTokens(child.Value, name, matches);
else if (containerToken.Type == JTokenType.Array)
foreach (JToken child in containerToken.Children())
FindTokens(child, name, matches);