cottle icon indicating copy to clipboard operation
cottle copied to clipboard

Improvement: JSON to Dictionary<Value, Value>

Open otdavies opened this issue 2 years ago • 4 comments

Hey there,

It would be mighty convenient if there was a utility function for going directly from JSON into Dictionary<Value, Value>.

Thanks!

otdavies avatar Apr 16 '23 08:04 otdavies

Hey,

Yes indeed it would, but wouldn't it also require to reference a json library from Cottle? To avoid this I would rather imagine a separate package to do this glue, wdyt?

r3c avatar Apr 16 '23 08:04 r3c

Maybe an example, e.g. something like this but a bit more official:

using System.Collections.Generic;
using Cottle;
using Newtonsoft.Json.Linq;

public class TemplateRenderer
{
    private readonly Dictionary<Value, Value> _values = new();

    public TemplateRenderer(string json)
    {
        AddToValuesDictionary(json);
    }
    
    public void AddToValuesDictionary(string jsonString)
    {
        // Parse the JSON string into a JObject
        var jObject = JObject.Parse(jsonString);

        // Iterate through the properties of the JObject
        foreach (var property in jObject.Properties())
        {
            // Convert the property key to a Value
            Value key = Value.FromString(property.Name);

            // Convert the property value to a Value using JTokenToValue
            Value value = JTokenToValue(property.Value);

            // Add the KeyValuePair to the result dictionary
            _values.Add(key, value);
        }
    }

    private Value JTokenToValue(JToken token)
    {
        switch (token.Type)
        {
            case JTokenType.Boolean:
                return Value.FromBoolean(token.ToObject<bool>());
            case JTokenType.Integer:
                return Value.FromNumber(token.ToObject<int>());
            case JTokenType.Float:
                return Value.FromNumber(token.ToObject<float>());
            case JTokenType.String:
                return Value.FromString(token.ToObject<string>());
            case JTokenType.Array:
                var arrayValues = new List<Value>();
                foreach (var item in token)
                {
                    arrayValues.Add(JTokenToValue(item));
                }
                return Value.FromEnumerable(arrayValues);
            case JTokenType.Object:
                return Value.FromDictionary(JsonToValueDictionary(token.ToString()));
            default:
                return Value.Undefined;
        }
    }

    private Dictionary<Value, Value> JsonToValueDictionary(string jsonString)
    {
        var result = new Dictionary<Value, Value>();

        // Parse the JSON string into a JObject
        var jObject = JObject.Parse(jsonString);

        // Iterate through the properties of the JObject
        foreach (var property in jObject.Properties())
        {
            // Convert the property key to a Value
            Value key = Value.FromString(property.Name);

            // Convert the property value to a Value using JTokenToValue
            Value value = JTokenToValue(property.Value);

            // Add the KeyValuePair to the result dictionary
            result.Add(key, value);
        }

        return result;
    }

    public void ClearValuesDictionary()
    {
        _values.Clear();
    }

    public string Render(string template)
    {
        var document = Document.CreateDefault(template).DocumentOrThrow;
        var result = document.Render(Context.CreateBuiltin(_values));
        return result;
    }
}

otdavies avatar Apr 16 '23 08:04 otdavies

Hey,

Yes indeed it would, but wouldn't it also require to reference a json library from Cottle? To avoid this I would rather imagine a separate package to do this glue, wdyt?

I don't disagree, would be nice to have an example though. This issue will come up in search results now, so you may not need to do anything beyond leaving this issue here. People looking for a quick solution to this will land here. =D.

Also thanks for providing this tool and supporting it <3

otdavies avatar Apr 16 '23 08:04 otdavies

Thanks for posting this code sample 👍 You're right leaving it as is already provides a valuable sample 🙂 If other people are interested, I'm definitely open to including this helper in some sibling assembly 🙂

r3c avatar Apr 16 '23 09:04 r3c