Question35799010 edit JSON via JSONPath

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Collections;
using System.Runtime.Serialization;
using System.Dynamic;

using Newtonsoft.Json;
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())
            {
                if (value == root)
                    root = JToken.FromObject(newValue);
                else
                    value.Replace(JToken.FromObject(newValue));
            }

            return root;
        }    

        public static string ReplacePath<T>(string jsonString, string path, T newValue)
        {
            return JToken.Parse(jsonString).ReplacePath(path, newValue).ToString();
        }    
    }

    public class TestClass
    {
        static string GetJson()
        {
            var json = @"{ ""store"": {
    ""book"": [ 
      { ""category"": ""reference"",
        ""author"": ""Nigel Rees"",
        ""title"": ""Sayings of the Century"",
        ""price"": 8.95
      },
      { ""category"": ""fiction"",
        ""author"": ""Evelyn Waugh"",
        ""title"": ""Sword of Honour"",
        ""price"": 12.99
      },
      { ""category"": ""fiction"",
        ""author"": ""Herman Melville"",
        ""title"": ""Moby Dick"",
        ""isbn"": ""0-553-21311-3"",
        ""price"": 8.99
      },
      { ""category"": ""fiction"",
        ""author"": ""J. R. R. Tolkien"",
        ""title"": ""The Lord of the Rings"",
        ""isbn"": ""0-395-19395-8"",
        ""price"": 22.99
      }
    ],
    ""bicycle"": {
      ""color"": ""red"",
      ""price"": 19.95
    }
  }
}";
            return json;
        }

        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)
        {
            Console.WriteLine(s);
            Debug.WriteLine(s);
        }
    }

	public class Program
	{
		public static void Main()
		{
			Console.WriteLine(string.Format("Json.NET version: {0}.\n", typeof(JsonSerializer).Assembly.FullName));			
			
			TestClass.Test();
		}
	}
;