JSON.stringify 忽略一些对象成员
这是一个简单的例子。
function Person() {
this.name = "Ted";
this.age = 5;
}
persons[0] = new Person();
persons[1] = new Person();
JSON.stringify(persons);
如果我有一个 Person 对象的数组,并且我想将它们字符串化。如何返回仅包含名称变量的 JSON。
原因是,我有带有递归引用的大型对象,这会导致问题。我想从字符串化过程中删除递归变量和其他变量。
感谢您的帮助!
Heres a simple example.
function Person() {
this.name = "Ted";
this.age = 5;
}
persons[0] = new Person();
persons[1] = new Person();
JSON.stringify(persons);
If I have an array of Person objects, and I want to stringify them. How can I return JSON with only the name variable.
The reason for this is, I have large objects with recursive references that are causing problems. And I want to remove the recursive variables and others from the stringify process.
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
最简单的答案是指定属性来字符串化,
另一个选项是向对象添加 toJSON 方法
: http://www.json.org/js.html
the easiest answer would be to specify the properties to stringify
another option would be to add a toJSON method to your objects
more: http://www.json.org/js.html
如果您仅支持 ECMAScript 5 兼容环境,则可以通过使用
Object.defineProperty()
[docs] 或Object.defineProperties()
[文档]。If you're only supporting ECMAScript 5 compatible environments, you could make the properties that should be excluded non-enumerable by setting them using
Object.defineProperty()
[docs] orObject.defineProperties()
[docs].我会创建一个新数组:
I would create a new array:
查看这篇文章指定您想要包含的字段。
JSON.stringify(person,["姓名","地址","线路1","城市"])
它比上面建议的更好匹配!
see this post specify the field you'd like to include.
JSON.stringify(person,["name","Address", "Line1", "City"])
it is match better then what suggested above!