Is it possible to exclude certain fields from being included in the json string?
Here is some pseudo code
var x = {
x:0,
y:0,
divID:\"xyz
I know this is already an answered question, but I'd like to add something when using instatiated objects.
If you assign it using a function, it will not be included on the JSON.stringify() result.
To access the value, call it as a function as well, ending with ()
var MyClass = function(){
this.visibleProperty1 = "sample1";
this.hiddenProperty1 = function(){ return "sample2" };
}
MyClass.prototype.assignAnother = function(){
this.visibleProperty2 = "sample3";
this.visibleProperty3 = "sample4";
this.hiddenProperty2 = function(){ return "sample5" };
}
var newObj = new MyClass();
console.log( JSON.stringify(newObj) );
// {"visibleProperty1":"sample1"}
newObj.assignAnother();
console.log( JSON.stringify(newObj) );
// {"visibleProperty1":"sample1","visibleProperty2":"sample3","visibleProperty3":"sample4"}
console.log( newObj.visibleProperty2 ); // sample3
console.log( newObj.hiddenProperty1() ); // sample2
console.log( newObj.hiddenProperty2() ); // sample5
You can also play around with the concept even when not on instatiated objects.
abstract class Hideable {
public hidden = [];
public toJSON() {
var result = {};
for (var x in this) {
if(x == "hidden") continue;
if (this.hidden.indexOf(x) === -1) {
result[x] = this[x];
}
}
return result;
};
}
This is an old question, but I'm adding an answer as there is a much simpler way to deal with this. Pass an array of strings that you wish to output in the JSON.
var x = {
x:0,
y:0,
divID:"xyz",
privateProperty1: 'foo',
privateProperty2: 'bar'
}
JSON.stringify(x, ["x", "y", "divID"]);
// This will output only x y and divID
// {"x":0,"y":0,"divID":"xyz"}
Note for Miroslaw Dylag's answer: The defined property should be its own property. Otherwise it would fail.
Doesn't work:
class Foo {
}
Object.defineProperty(Foo.prototype, 'bar', { value: 'bar', writable: true });
const foo = new Foo();
foo.bar = 'baz';
alert(JSON.stringify(foo).indexOf('bar') === -1); // false (found)
Works:
class Foo {
constructor() {
Object.defineProperty(this, 'bar', { value: 'bar', writable: true });
}
}
const foo = new Foo();
foo.bar = 'baz';
alert(JSON.stringify(foo).indexOf('bar') === -1); // true (not found)
You can use native function defineProperty from Object:
var data = {a: 10};
Object.defineProperty(data, 'transient', {value: 'static', writable: true});
data.transient = 'dasda';
console.log(JSON.stringify(data)); //{"a":10}
Easier way to do.
~~~
var myobject={
a:10,
b:[]
};
myobject.b.hidden1 = 'hiddenValue1';
myobject.b.hidden2 = 'hiddenValue2';
//output of stringify
//{
// "a": 10,
// "b": []
//}
~~~
http://www.markandey.com/2015/07/how-to-hide-few-keys-from-being-being.html