Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a string into a hashtable

Is there an easy (maybe even single and simple command) way to build a hashtable (associative array, JSON - whatever) from a string that includes key-value pairs, separated by a given delimiter.

Example:

n1=v1&n2=v2&n3=v3 (where & is a delimiter) should return: [{n1:v1}, {n2:v2}, {n3:v3}]

Example 2:

n1=v1;n2=v2;n3=v3 (where ; is a delimiter)

Thanks!

like image 912
BreakPhreak Avatar asked Nov 29 '22 15:11

BreakPhreak


2 Answers

The following will do it in a pretty basic way and does a check that the key in each case is not empty. All values will be strings.

function parse(str, separator) {
    var parsed = {};
    var pairs = str.split(separator);
    for (var i = 0, len = pairs.length, keyVal; i < len; ++i) {
        keyVal = pairs[i].split("=");
        if (keyVal[0]) {
            parsed[keyVal[0]] = keyVal[1];
        }
    }
    return parsed;
}

Example:

var props = parse("n1=v1&n2=v2&n3=v3", "&");
alert(props.n2); // Alerts v2
like image 100
Tim Down Avatar answered Dec 10 '22 19:12

Tim Down


Assuming you're using a modern browser:

str = "n1=v1&n2=v2&n3=v3"
delim = "&"

obj = str.split(delim).
    map(function(s) { return s.split("=") }).
    reduce(function(p, s) { return p[s[0]] = s[1], p }, {})

map, reduce

As a bonus, this also scales quite well when running in a cloud (see http://en.wikipedia.org/wiki/MapReduce).

like image 41
georg Avatar answered Dec 10 '22 19:12

georg