fParse

A fast, flexible and forgiving data structure parser.

by Hans PUFAL

JavaScript

function fParse (src) { 'use strict'; //======================================= fParse ===
  /* fParse   : a fast, flexible, forgiving data structure parser
     Author   : Hans B PUFAL  <Name>.<SURNAME>@gmail.com
     Source   : http://jsfiddle.net/jstoolsmith/BvWQH/
     Licence  : MIT

  */
  var valRE = /^\s*(?:([\[\{])(?!\s*[}\}])|(true|false|null|undefined)\s*(?=[;,}\]]|$)|([a-z_][-a-z_0-9]+)\s*[=:]|(\d\d*(?:\.\d*)?)|((?:'(?:\\.|[^\\']*)*')|(?:"(?:\\.|[^\\"]*)*"))|([a-z_][-a-z_0-9]+)\s*(?=[,;\]}]|$)|((?:\\.|[^;,\]}\\]*)*))\s*/i
              // regular expression to extract and categorise the next element in src
    , intrinsic = {'true': true, 'false': false, 'null': null, 'undefined': undefined}
              // Map intrinsic names to their values
    , rslt;       // Returned result

  function unEscape (s) {
    // Replace appropriate esacped characters in s
    return s.replace (/\\(.)/g, function (m, c) {
        return (c = 'nrbt\'"'.indexOf (c)) >= 0 ? '\n\r\b\t\'"'.slice (c, 1) : m;
    });
  }

  function scanner (closer) {
    // Scan the src string for the next object
    //   closer indicates what, if anything, should terminate the scan:
    //     ',' return just a single element
    //     '}' return an object
    //     ']' return an array

    var i             // item category index
      , m             // match array
      , obj = {}      // the result object
      , pCount = 0    // count of poperties added to obj
      , aIndex = -1;  // index of last added array value

    while (src && (m = src.match (valRE))) { // while is not empty and match succeeds
      src = src.slice (m[0].length); // remove scanned characters form src

      // The m array will have only two none empty elements: m[0] and the element corresponding
      //   to the category of the scanned item. Here we test each value of the array,
      //   setting i to the index of the none empty value and performing conversions.
      // Most items are converted to their...