简体   繁体   中英

Generate JSON from Nustache with proper escaping

I would like to use Nustache to generate JSON to talk to a specific webservice.

I do not want to do proper JSON-building using Newtonsoft or something like that because the specs for this webservice come as textfiles with placeholders. I agree that this is silly. So it makes sense to copy/massage/paste them into a template-format and hopefully make fewer mistakes.

But of course Nustache has no notion of what makes valid JSON.

With a template like

{ "foo": "{{bar}}" }

and a value for bar that needs escaping in JSON, say it includes curly brackets or an innocent backslash the result is string-replacy-correct, but not valid JSON.

Is there a way to tell Nustache that I want the output to be JSON and have it escape strings as it replaces them?

Or would you recommend doing a helper that can manage the escaping and put that on all the placeholders?

Thanks for reading and thinking.

I did not find a wholly satisfactory answer but a workable solution.

My workaround is a Nustache helper that takes care of the quoting and escaping. The ugly bit is that I need to specify the helper in the template in each instance:

{ "foo": "{{json bar}}" }

The helper implementation is trivial and can be listed fully here. For the actual work it delegates to JsonConvert from Newtonsoft JSON:

public class JSONHelpers
{
    public static void Register()
    {
        if (!Helpers.Contains("json"))
        {
            Helpers.Register("json", JSON);
        }       
    }

    private static void JSON(RenderContext ctx, IList<object> args, IDictionary<string, object> options,
                                     RenderBlock fn, RenderBlock inverse)
    {
        object input = args[0];
        if (input == null)
        {
            ctx.Write("null");
        }
        else
        {
            string text = input.ToString();
            string json = JsonConvert.ToString(text);
            ctx.Write(json);
        }
    }
}

Hopefully this comes useful to someone else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM