Search code examples
javascriptthymeleaf

put JSON object in thymeleaf with th tag


th:attr="data-params='{url:\'api/module/appId?appId='+${appId}+'\',dataName:\'module\'}'">

data-params should be a Json Object which i can use JSON.parse().And JSON.parse() needs Json Object like this {url: "/api/role/app?appId=d73ed474fca942609133b915c5da6d2a", dataName: "role"}

th:attr gets "{url:'api/module/appId?appId=d73ed474fca942609133b915c5da6d2a',dataName:'module'}"

Here is the question : how do i suppose to get right Json Object using th:attr ?


Solution

  • Escaping double quotes with " works for me:

    <span id="test" th:attr="data-params='{&quot;url&quot;:&quot;api/module/appId?appId='+${appId}+'&quot;,&quot;dataName&quot;:&quot;module&quot;}'" />
    

    Testing:

    <script>
        var json = $('#test').attr("data-params");
        console.log(json);
        console.log(JSON.parse(json));
    </script>
    

    Both Chrome and Firefox output correctly in their developer logs:

    {"url":"api/module/appId?appId=null","dataName":"module"}
    Object { url: "api/module/appId?appId=null", dataName: "module" }