Last active
June 21, 2024 14:23
-
-
Save kariudo/ae37e7904928d572f599a3e9cb9fd9c2 to your computer and use it in GitHub Desktop.
C# Nested JSON Regex Replacer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using Newtonsoft.Json.Linq; | |
using System; | |
using System.Text.RegularExpressions; | |
public class Program | |
{ | |
public void Main(string[] args) | |
{ | |
string jsonString = @"{""people"":[{ | |
""name"": ""John Doe"", | |
""age"": 60, | |
""address"": { | |
""street"": [""123 Main St"", {""vacation"": ""244 Main st""}], | |
""city"": ""Sometown, USA"" | |
} | |
}]}"; | |
var jsonObj = JsonConvert.DeserializeObject<JObject>(jsonString); | |
string regex = "(\\d+) Main"; // Replace main street address with elm | |
string replacement = "$1 Elm"; | |
var replacedObj = JsonReplacer.ReplaceValues(jsonObj, regex, replacement); | |
Console.WriteLine(replacedObj.ToString()); | |
} | |
} | |
public static class JsonReplacer | |
{ | |
public static JObject ReplaceValues(JObject obj, string regex, string replacement) | |
{ | |
JObject newObj = new JObject(); | |
foreach (var prop in obj.Properties()) | |
{ | |
if (prop.Value.Type == JTokenType.String) | |
{ | |
newObj[prop.Name] = JToken.FromObject(Regex.Replace(prop.Value.ToString(), regex, replacement)); | |
} | |
else if (prop.Value.Type == JTokenType.Object) | |
{ | |
// dive object for more values | |
newObj[prop.Name] = ReplaceValues((JObject)prop.Value, regex, replacement); | |
} | |
else if (prop.Value.Type == JTokenType.Array) | |
{ | |
var newArray = new JArray(); | |
foreach (var item in (JArray)prop.Value) | |
{ | |
if (item.Type == JTokenType.Object) | |
{ | |
newArray.Add(ReplaceValues((JObject)item, regex, replacement)); | |
} | |
else if (item.Type == JTokenType.String) | |
{ | |
newArray.Add(JToken.FromObject(Regex.Replace((string)item, regex, replacement))); | |
} | |
else | |
{ | |
// Handle other types | |
newArray.Add(item); | |
} | |
} | |
newObj[prop.Name] = newArray; | |
} | |
else | |
{ | |
// Handle other types | |
newObj[prop.Name] = prop.Value; | |
} | |
} | |
return newObj; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a sloppy example and the type check and replacement part would be DRYer to extract as well. But it shows the concept.