是否可以将 JavaScript EventSource 对象(其数字和字符串属性)转换为 JSON?

问题描述 投票:0回答:1

我很好奇 JavaScript EventSource 和其他具有数字和字符串属性的类似对象如何转换为 JSON。
我尝试了一些

JSON.stringify(...)
eventSource.entries()
的东西,但我得到了空的 JSON。

我知道我可以简单地

console.log(eventSource)

我很好奇是否可以不使用
console.log(...)
将其设为 JSON。

javascript json
1个回答
0
投票

到目前为止,我最好的尝试是使用

JSON.stringify(...)
放置我自己新创建的对象,该对象是根据我可以在
console.log(eventSoure)
输出中看到的 EventSource 对象的对象属性创建的。
我怀疑它是否有任何实用价值。
只是想在页面上看到它的更新,而不是在浏览器控制台中。

当然,属性 CONNECTING、OPEN 和 CLOSE 只是 readState 属性的一组可能值,添加它们只是为了在页面上看到它们。

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>

© www.soinside.com 2019 - 2024. All rights reserved.