What I have
I have templates that are stored in a database, and JSON data that gets converted into a dictionary in C#.
Example:
Template: “Hi {FirstName}”
Data: “{FirstName: ‘Jack’}”
This works easily with one level of data by using a regular expression to pull out anything within {} in the template.
What I want
I would like to be able to go deeper in the JSON than the first layer.
Example:
Template: “Hi {Name: {First}}”
Data: “{Name: {First: ‘Jack’, Last: ‘Smith’}}”
What approach should I be taking? (and some guidance on where to start with your pick)
- A regular expression
- Not use JSON in the template (in favor of xslt or something similar)
- Something else
I’d also like to be able to loop through data in the template, but I have no idea at all where to start with that one!
Thanks heaps
Here is how I would do it:
Change your template to this format
Hi {Name.First}Now create a
JavaScriptSerializerto convert JSON inDictionary<string, object>Now the variable
dhas the values of your JSON in a dictionary.Having that you can run your template against a regex to replace
{X.Y.Z.N}with the keys of the dictionary, recursively.Full Example:
I didn’t handle exceptions (e.g. the value couldn’t be found), you can handle this case and return the matched value if it wasn’t found.
m.Valuefor the raw value orm.Groups[1].Valuefor the string between{}.