0

So, I'm having my data parsed to json and then put in the model attributes. Like this:

@RequestMapping("/{id}")
public String getNetworkDetails(Model model, @PathVariable String id) throws JsonProcessingException{

    model.addAttribute("poolHashrates", findAndDisplayDataService.getAllPools(Long.valueOf(id)));
    model.addAttribute("poolDataJson", findAndDisplayDataService.returnPoolsAsJson(Long.valueOf(id)));

    return "networkDetails :: modalContents";
}

Next I'm trying to assign a poolDataJson string to a JS variable in html fragment through:

<script>
    var data = eval('('+'${poolDataJson}'+')');
    console.log(data);
</script>

What I would like to do with the data, is pass it to external JavaScript file as a data for my pie-chart. But first I'm getting an error on a string assignment:

Uncaught SyntaxError: Unexpected token {

What am I missing?

EDIT

I have also tried assigning json string to hidden input via:

<input type="hidden" id="networkId" th:value="${poolDataJson}"/></td>

And then read it with:

var data = document.getElementById('networkId').innerHTML;
console.log(data);

But again, nothing prints in console. When I put the ${poolDataJson} in

it prints properly on a page...

2
  • Try assigning poolDataJson to variable like var data = ${poolDataJson}; an then pass data into eval. Commented May 22, 2018 at 8:27
  • Same. Unexpected token on var json = ${poolDataJson}; Commented May 22, 2018 at 8:33

1 Answer 1

1

You shouldn't be returning a String as JSON text. Instead, you should return regular Java objects and then evaluate it like this (thymeleaf will automatically convert objects to JSON):

<script th:inline="javascript">
var data = /*[[${poolDataJson}]]*/ {};
console.log(data);
</script>

As for your errors. I would have to guess that your method findAndDisplayDataService.returnPoolsAsJson is returning invalid JSON. Without a real example, it's hard to tell.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.