Descent recursive json parser (created for educational reasons, do not use it in production)
In order to play with json_parser:
- install Node.js (click here to see a way to install it on your system)
- clone json_parser with
git clone [email protected]:Nazar910/json_parser.git
- cd into location where you cloned json_parser
cd ~/Documents/examples/json_parser
- install dependencies
npm install
- run tests (optional)
npm test
- run following command, where flag
f
points to json file you need to parse
node src/runner.js -f /tmp/example.json
Also you can require it and use in your node.js code (I don't know for what reason but you can)
const parse = require('./json_parser/src/index');
console.log(parse('{"foo":"bar"}'));
Inspired by a series of articles about interpeters at https://ruslanspivak.com (click to see the first article about interpeters)
Json parser consists of two main parts: Lexer and Parser. Both of them work with Tokens.
Token is a atomic part of the grammar. In this example it may be type of NUMBER
with value 5
. Generally it is a just an object that has type and value. See implementation here.
Lexer component is implemented as class (see src/lexer.js). It gets a json string as his input, and provides a stream of tokens: for each call of getNextToken()
you'll get new Token object, untill EOF.
Parser is a component which validates token order and creates object from json string on the fly. As input it accepts lexer object. Method parse
is the main method that returns object parsed from json string. See Parser implementation here.