0

I need to declare two variables having the same value, in fact a parsed json. They should not refer to the same object.

Is there a better way to do it than declaring the variables separately with the same value, i.e.

    var a = JSON.parse(myJson),
        b = JSON.parse(myJson);
marcosh
  • 8,780
  • 5
  • 44
  • 74
  • That's probably the best thing to do, as deep copies can be problematic and parsing is pretty fast unless the JSON is enormous (in which case the deep copy would be slow too of course). (Actually I guess a deep copy of a just-parsed blob of JSON would not run into anything complicated like cycles, but I'd still just parse twice.) – Pointy Feb 13 '14 at 17:06
  • You might want to look into cloning JavaScript objects: http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object – Frithjof Feb 13 '14 at 17:08
  • @Pointy thanks, I was trying to avoid all this duplication sice I have to do it for more than 10 variables... but if it's the better way to go, I'll stick to it – marcosh Feb 13 '14 at 17:08
  • possible duplicate of [Copy a variable's value into another](http://stackoverflow.com/questions/18829099/copy-a-variables-value-into-another) – Skwal Feb 13 '14 at 17:09

2 Answers2

0

since my variable a is just a non nested array, I think that the best way to go is to use

b = a.slice();
marcosh
  • 8,780
  • 5
  • 44
  • 74
0

To convert a JSON text into an object, you can use the eval() function. The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. To defend it, a JSON parser should be used. (link)

If you look at the JSON.parse (by Doughlas Crockford), It mostly prepares a string for eval. So you can save the prepared string & use eval on it.

JSON.prepare = function(text) {
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    cx.lastIndex = 0;
    if (cx.test(text)) {
        text = text.replace(cx, function (a) {
            return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        });
    }
    if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

        return '(' + text + ')';
    }
};

And using it as :

myJson = JSON.prepare(myJson); 

var a = eval(myJson),
    b = eval(myJson);
loxxy
  • 12,990
  • 2
  • 25
  • 56