Read-only JSON object in node.js

I need to give the result to users as a JSON object, and I cache the result.

In some cases, users change this result object, and a modified version is available to consecutive users. To avoid this, I am currently cloning the result, but this leads to heavy overhead as a very large JSON object.

So, I want JSON to read only to give a result and avoid the cloning process. How to make a JSON object inaccessible for editing?

+4
source share
2 answers

You can use Object.freeze () for this:

var obj = {a: 'a', b: 'b'};
var freezeObj = Object.freeze(obj);

freezeObj.a = 'c';

console.log("%j", freezeObj);   // prints {"a":"a","b":"b"}
console.log("%j", obj);         // prints {"a":"a","b":"b"}
console.log(obj === freezeObj); // prints true
+1
source

Object.freeze . :

var ObjConstrunctor = {}.constructor;

function isJSONObject(obj) {
    if (obj === undefined || obj === null || obj === true || obj === false || typeof obj !== "object" || Array.isArray(obj)) {
        return false;
    } else if (obj.constructor === ObjConstrunctor) {
        return true;
    } else {
        return false;
    }
}

function freezeObject(obj) {
    if (Array.isArray(obj)) {
        Object.freeze(obj);
        for (var i = 0; i < obj.length; i++) {
            freezeObject(obj[i])
        }
    } else if (isJSONObject(obj)) {
        Object.freeze(obj);
        for (var k in obj) {
            freezeObject(obj[k])
        }
    }
}

freezeObject(obj); 
+1

All Articles