Skip to content

Commit

Permalink
Add JSONTree
Browse files Browse the repository at this point in the history
  • Loading branch information
dabbott committed Dec 15, 2023
1 parent c9d663b commit 193016f
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/__tests__/__snapshots__/jsonTree.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`displays json tree diagram 1`] = `
"<Object>
├── null: null
├── boolean: true
├── number: 42
├── string: \\"hello\\"
├── multilineString: \\"line1\\\\nline2\\"
├── array: <Array>
│ ├── 0: 1
│ ├── 1: 2
│ └── 2: 3
└── object: <Object>
└── foo: \\"bar\\""
`;
15 changes: 15 additions & 0 deletions src/__tests__/jsonTree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { JSONTree } from '../trees/JSONTree'

it('displays json tree diagram', () => {
expect(
JSONTree.diagram({
null: null,
boolean: true,
number: 42,
string: 'hello',
multilineString: 'line1\nline2',
array: [1, 2, 3],
object: { foo: 'bar' },
})
).toMatchSnapshot()
})
33 changes: 33 additions & 0 deletions src/trees/JSONTree.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { defineTree } from '../defineTree'

export type JSONValue =
| string
| number
| boolean
| null
| JSONValue[]
| { [key: string]: JSONValue }

export const JSONTree = defineTree({
getEntries(node: JSONValue) {
if (typeof node === 'object' && node !== null) {
return Object.entries(node)
} else {
return []
}
},
}).withOptions({
getLabel(node, keyPath) {
const key = keyPath[keyPath.length - 1]
const text = printJSONValue(node)
return key === undefined ? text : key + ': ' + text
},
})

function printJSONValue(value: JSONValue): string {
if (typeof value === 'object' && value !== null) {
return `<${Object.prototype.toString.call(value).slice(8, -1)}>`
} else {
return JSON.stringify(value)
}
}

0 comments on commit 193016f

Please sign in to comment.