Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and

### Added
- Pin your favourite tools to the top. Use the pin next to any tool's name, or Pin in the ⌘K palette, and the tool appears in a Pinned section at the top of the sidebar and the home page, in order, with its ⌘1–⌘9 shortcut shown beside it. Up to nine tools can be pinned.
- JSON Formatter: narrow the output to one part of the document. Select a node in Tree view and press Filter, or type a path into the new Filter field as `.items[0].id`, `items[0].id`, `$.items[0].id` or `/items/0/id`. Both the text output and the tree show just that node, and Copy copies just that node. Copied paths still point into the whole document. A path that doesn't match says where it stopped (`.items has 3 items; there is no [5]`), and the ↑ button moves up one level.

### Fixed
- On phones, the GitHub and Settings icons at the top right no longer have a wide empty gap between them.
Expand Down
4 changes: 3 additions & 1 deletion packages/core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and

## [Unreleased]

Nothing yet.
### Added
- `/json`: `selectPath(root, path)` narrows a document to the node a path points at. The path can be a JSON pointer, a dot path or a jq path, and the result is `{ ok, value, path }` with array steps as numbers. When nothing matches, it returns a message saying where the walk stopped, written in the same path style that was typed. Also added `detectPathFlavor` and `formatPath`.
- `/json`: `parseDotPath` also reads a JSONPath-style `$.` or `$[` root.

## [0.2.0] — 2026-10-29

Expand Down
94 changes: 94 additions & 0 deletions packages/core/src/json/paths.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@ import { describe, expect, it } from 'vitest'
import { toDotPath, toJsonPointer } from './embedded.ts'
import {
MISSING,
detectPathFlavor,
formatPath,
parseDotPath,
parseJqPath,
parsePointer,
resolvePath,
selectPath,
toJqPath,
} from './paths.ts'
import { allContainerPointers, flattenTree, pathOf } from './tree.ts'
Expand Down Expand Up @@ -90,3 +93,94 @@ describe('round-trip properties', () => {
)
})
})

describe('parseDotPath with a JSONPath root', () => {
it('reads $. and $[ as the root marker', () => {
expect(parseDotPath('$.items[0].id')).toEqual(['items', 0, 'id'])
expect(parseDotPath('$[0]')).toEqual([0])
expect(parseDotPath('$ref.a')).toEqual(['$ref', 'a'])
})
})

describe('detectPathFlavor', () => {
it('tells the flavours apart by their first character', () => {
expect(detectPathFlavor('/items/0')).toBe('pointer')
expect(detectPathFlavor('.items[0]')).toBe('jq')
expect(detectPathFlavor('items[0]')).toBe('dot')
expect(detectPathFlavor('[0].id')).toBe('dot')
expect(detectPathFlavor('$.items')).toBe('dot')
})
})

describe('selectPath', () => {
const data = { items: [{ id: 7, tags: ['a'] }], 'a b': null, '': 'empty' }

it('selects the same node from every flavour', () => {
for (const src of ['/items/0/id', 'items[0].id', '.items[0].id', '$.items[0].id', ' .items[0].id ']) {
const r = selectPath(data, src)
expect(r).toMatchObject({ ok: true, value: 7, path: ['items', 0, 'id'] })
}
})

it('treats blank, "/", "." and "$" as the whole document', () => {
for (const src of ['', ' ', '/', '.', '$']) {
expect(selectPath(data, src)).toMatchObject({ ok: true, value: data, path: [] })
}
})

it('normalises pointer tokens into array indices', () => {
const r = selectPath(data, '/items/0/tags/0')
expect(r).toMatchObject({ ok: true, value: 'a', path: ['items', 0, 'tags', 0] })
})

it('reaches keys that are not identifiers', () => {
expect(selectPath(data, '.["a b"]')).toMatchObject({ ok: true, value: null })
expect(selectPath(data, '.[""]')).toMatchObject({ ok: true, value: 'empty' })
})

it('says where the walk stopped, in the flavour that was typed', () => {
expect(selectPath(data, '.items[0].nope')).toEqual({
ok: false,
flavor: 'jq',
message: '.items[0] has no key "nope"',
})
expect(selectPath(data, '/items/3')).toEqual({
ok: false,
flavor: 'pointer',
message: '/items has 1 item; there is no [3]',
})
expect(selectPath(data, 'items[0].id.x')).toEqual({
ok: false,
flavor: 'dot',
message: 'items[0].id is a number, so it has no children',
})
expect(selectPath(data, '/items/-')).toMatchObject({
ok: false,
message: '/items is an array; "-" is not an index',
})
expect(selectPath(data, '.missing')).toMatchObject({ ok: false, message: 'the root has no key "missing"' })
})

it('reports a malformed path instead of throwing', () => {
const r = selectPath(data, '.items[0')
expect(r.ok).toBe(false)
if (!r.ok) expect(r.message).toMatch(/^Not a valid path/)
})

it('agrees with resolvePath on every row of a document', () => {
const { expanded } = allContainerPointers(doc)
const rows = flattenTree(doc, expanded)
for (const [index] of rows.entries()) {
const path = pathOf(rows, index)
for (const flavor of ['pointer', 'dot', 'jq'] as const) {
const src = formatPath(path, flavor)
// '' as a pointer is the root, but so is '/' here; the one key that
// collides is the "" key, which needs the jq or dot form.
if (flavor === 'pointer' && path.length === 1 && path[0] === '') continue
const r = selectPath(doc, src)
expect(r).toMatchObject({ ok: true, path })
if (r.ok) expect(r.value).toBe(resolvePath(doc, path))
}
}
})
})
100 changes: 99 additions & 1 deletion packages/core/src/json/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
* than none.
*/

import { toDotPath, toJsonPointer } from './embedded.ts'
import { isRawNumber } from './rawjson.ts'
import { kindOf } from './tree.ts'

export type PathSegment = string | number

Expand Down Expand Up @@ -84,9 +86,17 @@ function parseAccessors(src: string, start: number, ident: RegExp): PathSegment[
return out
}

const DOT_IDENT = /^[A-Za-z_$][\w$]*/

/**
* Also reads a JSONPath-style `$.a[0]` / `$[0]` root. `toDotPath` never writes
* one (a leading `$` key comes out as `["$"]`), so this cannot misread a path
* it produced.
*/
export function parseDotPath(path: string): PathSegment[] {
if (path === '$') return []
return parseAccessors(path, 0, /^[A-Za-z_$][\w$]*/)
if (path.startsWith('$.') || path.startsWith('$[')) return parseAccessors(path, 1, DOT_IDENT)
return parseAccessors(path, 0, DOT_IDENT)
}

export function parseJqPath(path: string): PathSegment[] {
Expand Down Expand Up @@ -121,3 +131,91 @@ export function resolvePath(root: unknown, path: readonly PathSegment[]): unknow
}

export { MISSING }

export type PathFlavor = 'pointer' | 'dot' | 'jq'

/**
* Which flavour a typed path is in. The three are told apart by their first
* character, so detection never has to guess: `/` is a pointer, `.` is jq, and
* anything else is a dot path.
*/
export function detectPathFlavor(src: string): PathFlavor {
if (src === '' || src.startsWith('/')) return 'pointer'
if (src.startsWith('.')) return 'jq'
return 'dot'
}

export function formatPath(path: readonly PathSegment[], flavor: PathFlavor): string {
if (flavor === 'pointer') return toJsonPointer(path)
return flavor === 'jq' ? toJqPath(path) : toDotPath(path)
}

export type Selection =
| {
ok: true
value: unknown
/** Normalised: array steps are numbers, whatever flavour was typed. */
path: PathSegment[]
flavor: PathFlavor
}
| { ok: false; message: string; flavor: PathFlavor }

/**
* Narrow a document to the node a typed path points at, for "filter to this
* node". Accepts any of the three flavours, and JSONPath's `$.` root.
* Blank selects the whole document, and so does `/`, which is what the tree's
* Pointer button copies for the root; RFC 6901 would read it as the `""` key,
* which stays reachable as `.[""]`.
*
* Failures say where the walk stopped, written in the flavour that was typed,
* because "not found" alone sends you counting brackets.
*/
export function selectPath(root: unknown, src: string): Selection {
const text = src.trim()
const flavor = detectPathFlavor(text)
if (text === '' || text === '/') return { ok: true, value: root, path: [], flavor }

let segments: PathSegment[]
try {
segments =
flavor === 'pointer'
? parsePointer(text)
: flavor === 'jq'
? parseJqPath(text)
: parseDotPath(text)
} catch (e) {
return { ok: false, message: `Not a valid path: ${(e as Error).message}`, flavor }
}

const path: PathSegment[] = []
let node = root
for (const segment of segments) {
const here = path.length === 0 ? 'the root' : formatPath(path, flavor)
const kind = kindOf(node)
if (kind === 'array') {
const items = node as unknown[]
const i =
typeof segment === 'number' ? segment : /^(0|[1-9]\d*)$/.test(segment) ? Number(segment) : -1
if (i < 0) {
const message = `${here} is an array; ${JSON.stringify(segment)} is not an index`
return { ok: false, message, flavor }
}
if (i >= items.length) {
const noun = items.length === 1 ? 'item' : 'items'
return { ok: false, message: `${here} has ${items.length} ${noun}; there is no [${i}]`, flavor }
}
path.push(i)
node = items[i]
} else if (kind === 'object') {
const key = String(segment)
if (!Object.hasOwn(node as object, key)) {
return { ok: false, message: `${here} has no key ${JSON.stringify(key)}`, flavor }
}
path.push(key)
node = (node as Record<string, unknown>)[key]
} else {
return { ok: false, message: `${here} is a ${kind}, so it has no children`, flavor }
}
}
return { ok: true, value: node, path, flavor }
}
Loading
Loading