我很好奇 JavaScript EventSource 和其他具有数字和字符串属性的类似对象如何转换为 JSON。
我尝试了一些
JSON.stringify(...)
和 eventSource.entries()
的东西,但我得到了空的 JSON。
我知道我可以简单地
console.log(eventSource)
。console.log(...)
将其设为 JSON。
到目前为止,我最好的尝试是使用
JSON.stringify(...)
放置我自己新创建的对象,该对象是根据我可以在 console.log(eventSoure)
输出中看到的 EventSource 对象的对象属性创建的。const eventSource = new EventSource("https://example.com"); // will close immediately
console.log(eventSource); // to show the properties in console as well
setInterval(
() => {
document.querySelector("div").innerHTML = "<pre>" +
JSON.stringify({
addEventListener: eventSource.addEventListener, // native code skipped/not shown
CLOSED: eventSource.CLOSED,
CONNECTING: eventSource.CONNECTING,
onerror: eventSource.onerror,
onmessage: eventSource.onmessage,
onopen: eventSource.onopen,
OPEN: eventSource.OPEN,
readyState: eventSource.readyState,
url: eventSource.url,
withCredentials: eventSource.withCredentials
}, null, 2) + "</pre>";
},
1000
);
<div style="background:lightgrey"></div>