key-val-parser
This is a parser written in Javascript that helps parse key value pairs of the format "key1=value1 key2=value2". The resultant value is a JSON object that contains all the keys and their associated values. Additionally values might be quoted to contain sentences or multiple words that are space separated.
Motivation
I was writing a Slack app and I had to receive arguments as a series of key value pairs. I shopped around and didn't find a package that suited my needs.
Installation
npm install key-val-parser
Usage
var Parser=; var p=; var parsed=p; console;console;console;
The above code will produce
Number of keys parsed 2
value of name= john
value of age= 23
Examples
Regular Parser
var Parser=Parser;var p=; // Single key> p;Parsed username: 'john' // Multiple keys on the same line separated by whitespace> p;Parsed username: 'john' age: '23' // Single key with space between key, assignment operator and value> p;Parsed username: 'john' // Multiple keys with spaces between keys, assignment operator and values> p;Parsed username: 'john' age: '23' // Single key with quoted value> p;Parsed username: 'John Doe' // Multiple keys with quoted values> p;Parsed username: 'John Doe' address: 'No 1 Janpath, New Delhi' // Multiple keys with both quoted and unquoted values> p;Parsed username: 'johndoe' address: 'No 1 Janpath, New Delhi'
These are broadly the cases that it will cover.
Strict Parser
There is also a Strict Parser available that allows you to specify valid keys. If the parser encounters an invalid key, it will raise an error. This is useful in cases where you want to whitelist certain options. For example, a config file.
var StrictParser=StrictParser;var sp="name""age"; > sp // Error: Invalid key
Note: The rest of the parsing stays the same as a regular parser, and it will handle all the cases involving leading spaces, quotes etc.
Error handling
Errors will be thrown if the parser encounters missing keys, values or assignment operators.
var Parser=;var p=; // Missing valuep; // Error: missing value // Missing keyp; // Error: missing key // Missing assignment operatorp; // Error: missing assignment operator // Incomplete key value pairp; // Error: incomplete key value pair
Unsupported Cases
Keys with spaces
p;
Keys containing non-alphanumeric characters
p; // It will simply ignore special characters
Quoted keys
p;
Quoted values containing nested quotes
p;