Get started with pegjs CDN

MIT licensed

Peg.js is a production-ready, open-source parser generator for JS.

Tags:
  • parser
  • generator
  • peg

Stable version

Copied!

How to start using pegjs CDN


// Include PegJS from the CDN
const peg$ = require('pegjs')(pegjs => pegjs.Parser.fromString(pegjs.system, 'pegjs'));

// Define the grammar
const json = peg$('start', () => {
  '{' $('object') '}'

  function object() {
    return '{' + $('properties') + '}';

    function properties() {
      return $('property') + (() => {
        if (peek(2) === '{') return $('properties') + properties();
      })();
    }

    function property() {
      return $('string') + ': ' + $('value');

      function string() {
        return '"' + /[^"]+/.exec(expect('string'))[0] + '"';
      }

      function value() {
        if (/^{/.test(expect('value'))) return object();
        if (/[0-9]/.test(expect('value'))) return number();
        if (/["{}()]/.test(expect('value'))) return brackets();
        return '"' + expect('value') + '"';

        function number() {
          const number = /-?[0-9]+(\.[0-9]+)?/.exec(expect('value'))[0];
          consume(number.length);
          return Number(number);
        }

        function brackets() {
          consume('(');
          return array();
        }
      }
    }
  }
});

// Parse the input
const input = '{"name": "John", "age": 30, "hobbies": ["reading", "swimming"]}';
const result = json.parse(input);

// Output the result
console.log(result); // { name: 'John', age: 30, hobbies: [ 'reading', 'swimming' ] }
Copied!
Copied!

All versions