JSON.stringify不返回预期的对象 [英] JSON.stringify not returning expected objects

查看:114
本文介绍了JSON.stringify不返回预期的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我一直在使用Node.js和Websockets.我已经实现了,但是关于JSON.stringify(客户端)存在一个奇怪的问题.

I've been playing about with Node.js and Websockets recently. I'm getting there with it, however there's an odd issue regarding JSON.stringify (client side).

我喜欢使用JSON.stringify来确定服务器返回的对象属性.

I like to use JSON.stringify to determine which object properties the server is returning..

例如,我有以下代码片段:

So for example, I have the following snippet of code:

ws.onmessage = function(param1) {
    alert(JSON.stringify(param1));
}

这将显示一个{"isTrusted" : true}

由于此输出,我认为我的服务器没有将消息发送回客户端.出于好奇,我决定只将警报功能修改为

Because of this output, I thought my server wasn't sending a message back to the client. Out of curiousity, I decided to just modify the alert function to

alert(param1.data);

期望的消息在那里!所以我的问题是,为什么JSON.stringify在明显存在的地方没有包含data对象?

The expected message was there! So my question is why didn't JSON.stringify include a data object when it was evidently there?

推荐答案

JSON.stringify 在输出中仅包含对象的可枚举属性;这由抽象 SerializeJSONObject 操作覆盖在规格中.这意味着遗漏了继承的属性和不可枚举的属性.

JSON.stringify includes only the own, enumerable properties of an object in the output; this is covered by the abstract SerializeJSONObject operation in the spec. That means that inherited properties, and non-enumerable properties, are left out.

显然,邮件中唯一的,可枚举的属性是isTrusted.

Apparently, the only own, enumerable property on your message was isTrusted.

免费示例:

function Thingy(name, age) {
  // Save `name` as an own, enumerable property
  this.name = name;
  
  // Save `age` as an own, non-enumerable property
  Object.defineProperty(this, "age", {
    value: age
  });
}

// Define `what` as a property that will be inherited by
// all `Thingy` instances:
Thingy.prototype.what = "evs";

// Create one
var t = new Thingy("foo", 42);

// Get the JSON for it:
console.log(JSON.stringify(t)); // {"name":"foo"}

这里要讲的要点是,2016年几乎没有进行alert式调试的地方.而不是用alert(或console.log)手电筒在黑暗中绊倒,打开灯光:在处理程序中的第一条语句上放置一个断点,并在到达断点时动态检查param1的内容.它将显示您自己的属性和继承的属性,可枚举的属性和不可枚举的属性,以及它们的当前值和JavaScript代码已暂停.

The take-away message here, though, is that there's virtually no place for alert-style debugging in 2016. Instead of stumbling around in the dark with an alert (or console.log) torch, turn on the lights by using the powerful, fully-featured debugger built into your browser: Put a breakpoint on the first statement in your handler, and when the breakpoint is reached, examine the contents of param1 dynamically. It will show you both own properties and inherited ones, enumerable ones and non-enumerable ones, with their current values with the JavaScript code suspended.

这篇关于JSON.stringify不返回预期的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆