Languages

What is a JSON-safe object?

5 points
Asked by:
rmlocerd
212

Reading Kyle Simpson's book You Don't Know JS: this & Object Prototypes, I have found some term: JSON-safe object.

What it is?

1 answer
1 points
Answered by:
rmlocerd
212

It is object that can be converted to JSON without loosing any information.

That object shouldn't contain properties types that are not allowed in JSON notaiton.

Allowed are: POJO objects ({}), arrays, strings, numbers and booleans.

e.g.

// ONLINE-RUNNER:browser;

var userObject1 = {name: 'John', age: 23};
var userObject2 = JSON.parse(JSON.stringify(userObject1));

// deep equals operation for userObject1 and userObject2 should return true

console.log(JSON.stringify(userObject1));
console.log(JSON.stringify(userObject2));

Not JSON-safe object example:

// ONLINE-RUNNER:browser;

var userObject1 = {name: 'John', age: 23, expression: /^\d^/gi};
var userObject2 = JSON.parse(JSON.stringify(userObject1));

// in this case deep equals operation for userObject1 and userObject2 should return false

function printObject(object) {
	var text = '';
  	for (var key in object) {
      	if (text) {
        	text += ', ';
        }
    	text += key + '=' + object[key];
    }
  	console.log('{ ' + text + ' }');
}

printObject(userObject1);
printObject(userObject2);
0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join