skip to Main Content

I am curious how JavaScript EventSource and other similar objects having number and string properties can be converted to JSON.
I have tried some stuff with JSON.stringify(...) and eventSource.entries() but I get empty JSON.

I know that I can simply console.log(eventSource).
I am curious if I can make it a JSON not using console.log(...).

2

Answers


  1. Chosen as BEST ANSWER

    My best attempt so far has been to use JSON.stringify(...) putting my own newly created object created from object properties of an EventSource object I can see in console.log(eventSoure) output.
    I doubt if it is of any practical value.
    Just wanted to see it updated on the page and not in browser console.

    Of course, properties CONNECTING, OPEN and CLOSE are just a set of possible values of readyState property that are added solely to see them on the page as well.

    const eventSource = new EventSource("https://example.com"); // will close immediately
    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>


  2. You can extract all properties with walking the prototype chain and collecting properties you want.

    Use Object.getOwnPropertyNames() for that.

    For example I collect all primitive properties here:

    const getAllProps = (e, self = e) => {
      if(!e) return;
      const own = Object.getOwnPropertyNames(e).reduce((r, name) => {
        const val = self[name], type = typeof val;
        if(type !== 'object' && type !== 'function') r[name] = val;
        return r;
      }, {});
      return Object.assign(own, getAllProps(Object.getPrototypeOf(e), self));
    }
    
    document.addEventListener('click', e => {
      console.log(JSON.stringify(getAllProps(e), null, 2));
    });
    .as-console-wrapper{max-height:100%!important}
    Just click at any place
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search