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

2
  • Do you mean parsed as or from JSON? I.e. you have JSON and you want to convert it to a JavaScript object. Commented Mar 6, 2012 at 15:18
  • possible duplicate of how to parse json in javascript Commented Mar 6, 2012 at 15:19

3 Answers 3

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));
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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.
1

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

Comments

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/

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.