What is @mischnic/json-sourcemap?
@mischnic/json-sourcemap is an npm package that provides functionality to generate and work with source maps for JSON files. This can be particularly useful for debugging and understanding changes in JSON data structures by mapping positions in the JSON text to the corresponding data structures.
What are @mischnic/json-sourcemap's main functionalities?
Generating Source Maps
This feature allows you to generate a JSON string along with a source map that maps positions in the JSON text to the corresponding data structures.
const { stringify } = require('@mischnic/json-sourcemap');
const obj = { foo: 'bar', baz: [1, 2, 3] };
const { json, pointers } = stringify(obj);
console.log(json); // JSON string
console.log(pointers); // Source map
Parsing JSON with Source Maps
This feature allows you to parse a JSON string and generate a source map that maps positions in the JSON text to the corresponding data structures.
const { parse } = require('@mischnic/json-sourcemap');
const json = '{"foo":"bar","baz":[1,2,3]}';
const { data, pointers } = parse(json);
console.log(data); // Parsed JSON object
console.log(pointers); // Source map
Querying Source Maps
This feature allows you to query the source map to find the position of specific elements in the JSON text.
const { parse } = require('@mischnic/json-sourcemap');
const json = '{"foo":"bar","baz":[1,2,3]}';
const { data, pointers } = parse(json);
const pointer = pointers['/baz/1'];
console.log(pointer); // { value: 2, valueEnd: 16, key: '1', keyEnd: 15, parent: '/baz' }
Other packages similar to @mischnic/json-sourcemap
json-source-map
json-source-map is a package that provides similar functionality for generating and working with source maps for JSON files. It allows you to parse JSON strings and generate source maps, as well as query the source maps to find positions of elements in the JSON text. Compared to @mischnic/json-sourcemap, it offers a similar set of features but may have different performance characteristics or API design.
@mischnic/json-sourcemap
Generate positions for values in JSON and JSON5 strings.
Inspired by and mostly API-compatible with https://github.com/epoberezkin/json-source-map.
Usage
type Position = {
line: number;
column: number;
pos: number;
};
type Mapping =
| {
value: Position;
valueEnd: Position;
}
| {
value: Position;
valueEnd: Position;
key?: Position;
keyEnd?: Position;
};
export function parse(
json: string,
reviver?: (key: any, value: any) => any,
options?: {
tabWidth?: number;
useJSON5?: boolean;
}
): {
data: any;
pointers: Record<string, Mapping>;
};
The default tabWidth
is 4.
The valueEnd
and keyEnd
positions are exclusive. line
, column
and pos
are 0-based.