'How to ouput a json string in the js section of a html file using thymeleaf
I have a project with Java 8, bringing data to the frontend with Thymeleaf. The data entity I want to ouput in my frontend is calles logs and is a list of entities that have an attribute containig json data. I output it in the html file as follows:
<script type="text/javascript">
let logs = [[${logs}]];
</script>
The json has the following structure:
{
"oldest": 712367620,
"youngest": 712378606,
"measurements": []
}
But on the page it appears with the double quotes escaped which completely messes up the js:
<script type="text/javascript">
let logs = [LogEntity(id=52, success=true, runtimes={
"oldest" : 712367620,
"youngest" : 712378606,
"measurements" : []
})]
</script>
How can I prevent the escaping of the double quotes in the json string?
I work with php and twig in another project and there it is as simple as {{ logs|raw }}. Is there some kind of modifier in thymeleaf like |raw in php twig?
Security is not an issue since I have complete control over the data objects.
Solution 1:[1]
You have to enable JavaScript inlining with th:inline="javascript":
<script type="text/javascript" th:inline="javascript">
let logs = [[${logs}]];
</script>
(I'm not sure what you mean by "json data". Do you mean you have a String that contains JSON?)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Metroids |
