using System.Collections.Generic;
using System.Diagnostics;
using System.Collections;
using System.Runtime.Serialization;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
public static class JsonExtensions
public static JToken ReplacePath<T>(this JToken root, string path, T newValue)
if (root == null || path == null)
throw new ArgumentNullException();
foreach (var value in root.SelectTokens(path).ToList())
root = JToken.FromObject(newValue);
value.Replace(JToken.FromObject(newValue));
public static string ReplacePath<T>(string jsonString, string path, T newValue)
return JToken.Parse(jsonString).ReplacePath(path, newValue).ToString();
var json = @"{ ""store"": {
{ ""category"": ""reference"",
""author"": ""Nigel Rees"",
""title"": ""Sayings of the Century"",
{ ""category"": ""fiction"",
""author"": ""Evelyn Waugh"",
""title"": ""Sword of Honour"",
{ ""category"": ""fiction"",
""author"": ""Herman Melville"",
""title"": ""Moby Dick"",
""isbn"": ""0-553-21311-3"",
{ ""category"": ""fiction"",
""author"": ""J. R. R. Tolkien"",
""title"": ""The Lord of the Rings"",
""isbn"": ""0-395-19395-8"",
public static void Test()
var jsonString = GetJson();
ConsoleAndDebug.WriteLine("\nInitial JSON:\n");
ConsoleAndDebug.WriteLine(JToken.Parse(jsonString));
var newJsonAuthorString = JsonExtensions.ReplacePath(jsonString, @"$.store.book[*].author", "NewAuthorSpecifiedByUser");
ConsoleAndDebug.WriteLine("\nModified JSON author properties:\n");
ConsoleAndDebug.WriteLine(newJsonAuthorString);
var newJsonArrayString = JsonExtensions.ReplacePath(jsonString, @"$.store.book[*]", "NewAuthorSpecifiedByUser");
ConsoleAndDebug.WriteLine("\nModified JSON array elements:\n");
ConsoleAndDebug.WriteLine(newJsonArrayString);
var newJsonRootString = JsonExtensions.ReplacePath(jsonString, @"", new { author = "NewAuthorSpecifiedByUser" });
ConsoleAndDebug.WriteLine("\nModified JSON root element:\n");
ConsoleAndDebug.WriteLine(newJsonRootString);
public static class ConsoleAndDebug
public static void WriteLine(object s)
public static void Main()
Console.WriteLine(string.Format("Json.NET version: {0}.\n", typeof(JsonSerializer).Assembly.FullName));