gpt4 book ai didi

javascript - 使用 JSON.stringify 时输出不同

转载 作者:行者123 更新时间:2023-12-02 06:54:46 25 4
gpt4 key购买 nike

我正在使用 kendo UI,但我认为这是一个普遍的问题。

基本上我正在记录一个对象,结果如下所示,

enter image description here

然后我 JSON.stringify(obj),我得到这样的输出

{"ProductID":5,"ProductName":"Cream","UnitPrice":12,"Discontinued":false,"UnitsInStock":15,"Priority":5}

问题,有人可以说明为什么参数“dirty”,'uid'没有被字符串化吗?如果您真的可以发布一些创建此类对象的示例,那就太好了。

仅供引用:我的实际对象就像传递给 Kendo Grid 的 stringify 的输出,我从一种 kendo Grid 方法中获取脏对象(基本上给出了在网格中编辑的行集)

什么是认为它与 object.prototype 有关。也许父属性没有被字符串化......

最佳答案

JSON.stringify 仅包含对象的自己可枚举 属性,其名称为字符串。因此,可以通过三种方式将属性排除在外:如果它们是继承的,如果它们是不可枚举的(例如那些 Object.defineProperty 默认创建的),或者如果它们的名称不是t 字符串(ES2015 能够让属性具有 Symbol 名称而不是字符串名称)。

这演示了其中的两个方面,“自己的”和“可枚举的”方面:它记录 {"answer":42},例如,因为 obj 只有一个自己的可枚举属性,answerprop 是继承的,foo 是不可枚举的:

// An object to use as a prototype
var proto = {
prop: 1
};

// Create an object using that as its prototype
var obj = Object.create(proto);

// Define a non-enumerable property
Object.defineProperty(obj, "foo", {
value: 27
});

// Define an own, enumerable property
obj.answer = 42;

// Show the JSON for the object
snippet.log(JSON.stringify(obj));

这在 JSON.stringify 的规范中:

实例:

// An object to use as a prototype
var proto = {
prop: 1
};

// Create an object using that as its prototype
var obj = Object.create(proto);

// Define a non-enumerable property
Object.defineProperty(obj, "foo", {
value: 27
});

// Define an own, enumerable property
obj.answer = 42;

// Show the JSON for the object
snippet.log(JSON.stringify(obj));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

为了完整起见,这也演示了以 Symbol 命名的属性 ( live copy on Babel's REPL ):

// An object to use as a prototype
var proto = {
prop: 1
};

// Create an object using that as its prototype
var obj = Object.create(proto);

// Define a non-enumerable property
Object.defineProperty(obj, "foo", {
value: 27
});

// Define an own, enumerable property with a string name
obj.answer = 42;

// Define an own, enumerable property with a Symbol name
var s1 = Symbol();
obj[s1] = "I'm enumerable and have a Symbol name";

// Show the JSON for the object
console.log(JSON.stringify(obj)); // {"answer":42}

// Proof that the Symbol property was enumerable comes
// from Object.assign
var obj2 = Object.assign(obj);
console.log(obj2[s1]); // I'm enumerable and have a Symbol name

关于javascript - 使用 JSON.stringify 时输出不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33751803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com