Date: 2017-04-06 07:27 pm (UTC)
From: [personal profile] sassa_nf
Right. So how does one produce a flat structure from a tree?

function* toJSON(x) {
  if (typeof x === 'string') {
    yield '"';
    yield escape(x);
    yield '"';
    return;
  }
  if (typeof x === 'number') {
...  }
  if (typeof x === 'boolean'
...
  }
  yield '{';
  let first = true;
  for (let k in x) {
    if (!first) yield ',';
    first = false;
    yield '"' + k + '": ';
    yield* toJSON(x[k]);
  }
  yield '}';
}


Straightforward streaming of keys, values, delimiters. No one is aware of anyone's parents or children.

If we were to flatten it first, then somewhere need to distinguish that they are part of objects, so the correct keys can be produced in the output.

function* toJSON(k, x) {
  if (typeof x === 'object') {
    for (let k1 in x) {
      yield* toJSON(k? k + '.' + k1: k1, x[k1]);
    }
    return;
  }
  if (k) {
    yield '"';
    yield k;
    yield '":';
  }

  if (typeof x === 'string') {
    yield '"';
    yield escape(x);
    yield '"';
    return;
  }
  if (typeof x === 'number') {
...  }
  if (typeof x === 'boolean'
...
  }
}

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

May 2025

S M T W T F S
    1 2 3
456 7 8 9 10
11 121314151617
181920 21 222324
25 262728 2930 31

Most Popular Tags

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated Jun. 1st, 2025 08:43 am
Powered by Dreamwidth Studios