相关疑难解决方法(0)

隐藏JSON.stringify()输出中的某些值

是否可以排除某些字段包含在json字符串中?

这是一些伪代码

var x = {
    x:0,
    y:0,
    divID:"xyz",
    privateProperty1: 'foo',
    privateProperty2: 'bar'
}
Run Code Online (Sandbox Code Playgroud)

我想排除privateProperty1和privateproperty2出现在json字符串中

所以我想,我可以使用stringify替换器功能

function replacer(key,value)
{
    if (key=="privateProperty1") then retun "none";
    else if (key=="privateProperty2") then retun "none";
    else return value;
}
Run Code Online (Sandbox Code Playgroud)

并在stringify中

var jsonString = json.stringify(x,replacer);
Run Code Online (Sandbox Code Playgroud)

但是在jsonString中我仍然看到它

{...privateProperty1:value..., privateProperty2:value }
Run Code Online (Sandbox Code Playgroud)

我想要没有privateproperties的字符串.

javascript json

81
推荐指数
5
解决办法
6万
查看次数

原型上的Object.defineProperty阻止JSON.stringify序列化它

我正在使用TypeScript来定义一些类,当我创建一个属性时,它会生成Class1以下plunkr中的等价物:

http://plnkr.co/edit/NXUo7zjJZaUuyv54TD9i?p=preview

var Class1 = function () {
  this._name = "test1";
}

Object.defineProperty(Class1.prototype, "Name", {
  get: function() { return this._name; },
  set: function(value) { this._name = value; },
  enumerable: true
});

JSON.stringify(new Class1()); // Will be "{"_name":"test1"}"
Run Code Online (Sandbox Code Playgroud)

序列化时,它不会输出我刚刚定义的属性.

instance2并且instance3通过序列化已定义的属性来表现我的期望.(参见plunkr输出).

我的实际问题是:这是正常的吗?

如果是这样,我该如何以最有效的方式解决它?

javascript json typescript

18
推荐指数
3
解决办法
1万
查看次数

如何在 JavaScript 中枚举/发现 getter 和 setter?

我试图在打字稿中发现对象上的 getter 和 setter。我尝试过 Object.entries() 和 Object.keys() ,但这些都没有返回 getter 和 setter。我怎样才能列举这些呢?

编辑:这是一些显示问题的代码:

class ThingWithGetter{
  myProperty = 22;
  get myGetter() {return 1;}
}
const thing = new ThingWithGetter()

// Does not show getter
console.log(Object.keys(thing));

// Does not show getter
const descriptors = Object.getOwnPropertyDescriptors(thing);
console.log(Object.keys(descriptors));

// Does not show getter
console.log(Object.entries(thing))
Run Code Online (Sandbox Code Playgroud)

javascript

10
推荐指数
3
解决办法
3734
查看次数

JSON.stringify 仅序列化 TypeScript getter

我有以下类结构...

export abstract class PersonBase {
    public toJSON(): string {
        let obj = Object.assign(this);
        let keys = Object.keys(this.constructor.prototype);
        obj.toJSON = undefined;
        return JSON.stringify(obj, keys);
    }
}

export class Person extends PersonBase {

    private readonly _firstName: string;
    private readonly _lastName: string;

    public constructor(firstName: string, lastName: string) {
        this._firstName = firstName;
        this._lastName = lastName;
    }

    public get first_name(): string {
        return this._firstName;
    }

    public get last_name(): string {
        return this._lastName;
    }
}

export class DetailPerson extends Person {

    private _address: string;

    public …
Run Code Online (Sandbox Code Playgroud)

javascript json typescript

3
推荐指数
1
解决办法
2797
查看次数

标签 统计

javascript ×4

json ×3

typescript ×2