Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improvement: JSON to Dictionary<Value, Value> #189

Open
otdavies opened this issue Apr 16, 2023 · 4 comments
Open

Improvement: JSON to Dictionary<Value, Value> #189

otdavies opened this issue Apr 16, 2023 · 4 comments

Comments

@otdavies
Copy link

Hey there,

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

Thanks!

@r3c
Copy link
Owner

r3c commented Apr 16, 2023

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?

@otdavies
Copy link
Author

otdavies commented Apr 16, 2023

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
Copy link
Author

otdavies commented Apr 16, 2023

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

@r3c
Copy link
Owner

r3c commented Apr 16, 2023

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 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants