Search code examples
javascripttyped-arrays

Convert string to typed array in Javascript


I have a string that should be parsed to JSON and than should be converted to a Float32Array. The string looks like this:

{"vertices":"[-1.0, -1.0, -1.0, -1.0, -1.0, 0.0, 1.0, -1.0, 0.0]"}

The Array should be assigned to a variable, e.g.:

mesh.vertices = new Float32Array([-1.0, -1.0, -1.0, -1.0, -1.0, 0.0, 1.0, -1.0, 0.0]);

How can I convert the string so that the array consists of float numbers? For security reasons, I don´t want to use eval().


Solution

  • You could use JSON.parse:

    mesh.vertices = new Float32Array(JSON.parse(myString).vertices);
    

    This is assuming you meant:

    {"vertices":[-1.0, -1.0, -1.0, -1.0, -1.0, 0.0, 1.0, -1.0, 0.0]}
    

    If the JSON is actually as you said (which FWIW is a bit weird), it'd be:

    mesh.vertices = new Float32Array(JSON.parse(JSON.parse(myString).vertices));