Search code examples
javascriptjsongrailsgroovygsp

How to display the content of a two-dimensional array JSON Object in an HTML table


I'm trying to display the content of a Javascript object into an HMTL/CSS table. The two dimensional array in Groovy looks like this (It's just a snippet, not the full one) :

[[null, Pyjamas , Oreillers Traversins, Linge de lit, Protection literie, Surmatelas, Linge de lit , Couettes, Linge de bain], [Pyjamas , null, .3333333333333333, 0.16666666666666666, 0.16, 0.16, null, null, null]]

One array corresponds to one line in my table. The Javascript object is created from a groovy controller like this

[matrix: matrix as JSON]

And here is how I think I have to get the full table in GSP/Javascript and display it (in my console, not in my table)

<script>
  var matrix = ${matrix};
  var matrixTab = JSON.stringify(matrix);
  console.log(matrixTab);
</script>

What the HMTL table looks like doesn't really matter. One more thing, I'm using firebug and when i'm trying to catch my array, the console shows me this error. Any idea ?


Solution

  • JSON.stringify() will output an object as a string but matrix is not a valid JavaScript object here. ${matrix} needs to be a string containing your object and then parse it like this:

    var matrix = '[[null, Pyjamas , Oreillers Traversins, Linge de lit, Protection literie, Surmatelas, Linge de lit , Couettes, Linge de bain], [Pyjamas , null, .3333333333333333, 0.16666666666666666, 0.16, 0.16, null, null, null]]'
    // OR
    var matrix = ${matrix}
    var matrixTab = JSON.parse(matrix);
    

    You will be able to go through matrixTab and display the table as you need.