-3

I've been using treeify recently to display a nested JSON object as a tree, like the output of Linux CLI tool tree.

Is the same result doable with only JSON.stringify? I know JSON.stringify accepts 3 arguments: value, replacer and space (MDN JSON.strinfify documentation).

JSON.strinfify(value, replacer, space)

I ask the question as I discovered the space could be a String, and not only a Number.

The solution should be as generic as possible, but if any example is needed, refer to the one displaid on treeify page:

const x = {
  oranges: { mandarin: { clementine: null, tangerine: 'so cheap and juicy!' } },
  apples: { gala: null, 'pink lady': null },
  others: [ 'bananas', 'ananas', 'pear' ]
}
->
> console.log( treeify.asTree(x, true, true) )
├─ oranges
│  └─ mandarin
│     ├─ clementine
│     └─ tangerine: so cheap and juicy!
├─ apples
│  ├─ gala
│  └─ pink lady
└─ others
   ├─ 0: bananas
   ├─ 1: ananas
   └─ 2: pear

Is it possible to access the space argument from the replacer function as a starting point?

jgran
  • 1,111
  • 2
  • 11
  • 21

1 Answers1

1

JSON.stringify takes a constant value as spacer and it does not change for the nested items, which is necessary because you have two different strings for items and two as prefix for nested items.

Instead, you could take a custom function with a recursive approach by handing over the prefix for each line.

function getFormatted(object, prefix) {
    var result = '';
    Object.entries(object).forEach(([k, v], i, { length }) => {
        result += prefix + (i + 1 === length ? '└─ ' : '├─ ') + k;
        if (v && typeof v === 'object') {
            result += '\n';
            result += getFormatted(v, prefix + (i + 1 === length ? '   ': '│  '));
        } else {
            if (v) result += ': ' + v;
            result += '\n';
        }
    });
    return result;
}

const x = { oranges: { mandarin: { clementine: null, tangerine: 'so cheap and juicy!' } }, apples: { gala: null, 'pink lady': null }, others: ['bananas', 'ananas', 'pear'] };

console.log(getFormatted(x, ''))
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thank you for spending time on a so quickly downvoted question. Nice recursive function! Why was is it downvoted as I've learnt something anyway... – jgran Jan 17 '20 at 14:12