1

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().

maria90
  • 269
  • 4
  • 10
  • Do you mean parsed *as* or *from* JSON? I.e. you have JSON and you want to convert it to a JavaScript object. – Felix Kling Mar 06 '12 at 15:18
  • possible duplicate of [how to parse json in javascript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – Felix Kling Mar 06 '12 at 15:19

3 Answers3

2

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));
James M
  • 18,506
  • 3
  • 48
  • 56
  • Thanks! I will use {"vertices":[-1.0, -1.0, -1.0, -1.0, -1.0, 0.0, 1.0, -1.0, 0.0]} as you proposed. – maria90 Mar 06 '12 at 15:33
  • There is a good reason for "[ array, items]". It keeps json readable when using simplejson and python. Having 10,000 items in one row or in one column makes a difference. – Torsten Becker May 21 '12 at 22:49
1

Use JSON.parse to parse JSON data securely. See https://developer.mozilla.org/En/Using_native_JSON

0

I still suggest you to use the native JSON parser (as others mentioned), but here is a very simple and limited implementation:

var stringToParse = "{vertices:[-1.0, -1.0, -1.0, -1.0, -1.0, 0.0, 1.0, -1.0, 0.0]}";

Object.prototype.simpleParse = function() {
    if (!(this instanceof String)) throw "Type mismatch";
    var re = /(\w+)[^:]+:\[([^\]]+)\]/g;
    var keyvalues = re.exec(this.valueOf());
    var key = keyvalues[1];
    var values = keyvalues[2].split(",");
    var arr = [];
    for (val in values) {
        var currentValue = (/-?\d+(.\d+)?/).exec(values[val])[0];
        arr.push(currentValue);
    }
    arr.pop();
    ret = {};
    ret[key] = new Float32Array(arr);
    return ret;
}

console.log(stringToParse.simpleParse());

​Demo: http://jsfiddle.net/mKWGH/

fardjad
  • 20,031
  • 6
  • 53
  • 68