Escaping JSON Content with Keyword Replacements


(Squiz) #1

We've created an asset listing that generates a JSON output. The problem is that we can't escape the quote or backslash characters correctly. We've tried:


[list=1]

  • %keyword^escapequotes%, which also escapes single quotes and invalidates the JSON. This then fails to parse.
    [*]%keyword^[b]escapehtml[/b]%], which doesn't escape the backslash. Fails to parse.
    [*]%keyword^replace:":\"%, which holds the most promice doesn't appear to do anything.




    So with that out of the way, has anyone got any ideas as to how to escape double-quotes and backslashes in a keyword? Is there a way to specify these non-alpha characters as parameters in the replace keyword?

  • (Dan Simmons) #2

    Hey Ash, this is a tricky one that I ran into the other day as well. In the end I had to switch to XML. Did you try a double-backslash when using the replace modifier?


    Creating JSON is tricky anyway, because valid JSON isn't supposed to have trailing commas at the end of arrays and I can't think of a way to achieve this just with an asset listing by itself.


    (Nic Hubbard) #3

    [quote]
    Creating JSON is tricky anyway, because valid JSON isn't supposed to have trailing commas at the end of arrays and I can't think of a way to achieve this just with an asset listing by itself.

    [/quote]



    You can use a position format of -1 to indicate the last asset then use that without the trailing comma. I created valid JSON this way for an internal project that I built…


    (Dan Simmons) #4

    [quote]
    You can use a position format of -1 to indicate the last asset then use that without the trailing comma. I created valid JSON this way for an internal project that I built…

    [/quote]



    Wow, good tip! I wish I'd thought of that a couple of weeks ago…


    (Squiz) #5

    Turns out we don't have the replace keyword as we're still on 3.28.1. I guess that's why it doesn't do anything :wink:


    Pretty good incentive for an upgrade if you ask me though. Thanks for your ideas. :slight_smile:


    (Squiz) #6

    And voila. ^replace works a charm for escaping JSON, if it is a bit verbose:

        %asset_contents^replace:\\:\\\\^replace:":\"^replace:\t:\\t^nl2br%


    I haven't tested the tab replacement yet so it might not be completely working, but it works fine for otherwise escaping characters that fail validation.

    (Squiz) #7

    [quote]
    And voila. ^replace works a charm for escaping JSON

    [/quote]



    Turns out this doesn't work on %asset_metadata_X% and sprays PHP errors through the logs. Nice.