A JSON parser in TypeScript made from scratch without JSON.parse
or eval
.
parser.ts
exports the parse function as its default export.
import parse from "./parser.ts"
const result = parse(`{
"hello": "world",
"foo": "bar"
}`)
console.log(result) // { "hello": "world", "foo": "bar" }
parse(`{ "hello": "world", "foo": }`) // Error: Expected value at index 27
This parser passes 100% of the tests in JSON Parsing Test Suite.
To run tests locally, install Deno. Make a folder called tests
in this projects root directory. Copy the tests from test_parsing into tests
. Run deno run test.ts
.
This checks that:
- the parser errors on invalid json
- the parser succeeds on valid json
- on valid json, the resulting value matches
JSON.parse
JSON.parse
already exists, so I really just did this for fun! The awesome railroad diagrams on json.org made it really appealing.