4

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!

2
  • possible duplicate of How can I convert query string or JSON object map to single JSON object with jQuery? Commented Jan 30, 2012 at 12:53
  • That question is not quite the same as this question. Look at the difference in answers: none of the 7 versions of essentially the same code here is represented in the supposed duplicate. That said, I imagine there is an exact dupe somewhere. Commented Jan 30, 2012 at 13:05

10 Answers 10

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

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).

Comments

3

Note: this yields the specified [{n1:'v1'}, {n2:'v2'}] format, and not the { n1: 'v1', n2: 'v2' } format that'd better fit the Hashtable description.

If you can trust your input in all other regards than the delimiter, then it would look something like this:

function splitByDelimiter(input, delimiter) {
    var parts = input.split(delimiter);
    var output = [];
    for(var i = 0; i < parts.length; i++) {
        var item = {};
        var keyValue = parts[i].split('=');
        item[keyValue[0]] = keyValue[1];

        output.push(item);
    }
    return output;
}

splitByDelimiter('n1=v1;n2=v2;n3=v3', ';')

Comments

2
var stuff = "n1=v1&n2=v2&n3=v3".split("&"),
moreStuff = [],
hashStuff = {},
i = 0, l = stuff.length;

for (;i<l;i++) {
  moreStuff = stuff[i].split("=");
  hashStuff[moreStuff[0]] = moreStuff[1];
}

Comments

2

My try, not a efficient one :(

query  = 'n1=v1&n2=v2&n3=v3'.split('&')
obj = {}

$.each(arr,function(k,v){
key = v.split('=')[0]
value = v.split('=')[1];
obj[key] = value;
})

obj.n1 outputs v1

Comments

2
var str = "n1=v1&n2=v2&n3=v3";

var arr = eval('[{' + str.replace(/=/g, ':"').replace(/&/g, '"},{') + '"}]');

or if you don't prefer eval

var arr = jQuery.parseJSON('[{"' + str.replace(/=/g, '":"').replace(/&/g, '"},{"') + '"}]')

Comments

1

Regular expressions.

See this summary from http://www.regular-expressions.info/javascript.html (Regexp Methods of The String Class section):

Using a string's split() method allows you to split the string into an array of strings using a regular expression to determine the positions at which the string is splitted. E.g. myArray = myString.split(/,/) splits a comma-delimited list into an array. The comma's themselves are not included in the resulting array of strings.

EDIT

You can refer to this other question too: Parse query string in JavaScript

Comments

1

Not 'easy' as in 'built-in', but...

var myQueryString = "n1=v1&n2=v2&n3=v3";
var delim = '&';

var vars = myQueryString.split(delim);

var parsed = {};
for (var i=0; i<vars.length; i++) { 
    var kvPair = vars[i].split("="); 
    parsed[kvPair[0]] = kvPair[1];
}

Result is in parsed.

Comments

1
function parseStr2Map(str) {
    var elems = str.split("&");
    var map = {};
    for (var i = 0; i < elems.length; i++) {
        var nvPair = elems[i].split("=");
        map[nvPair[0]] = nvPair[1];
    }
    return map;
}

It's without errorhandling. If you want to parse location.search then you have to do the decode...

Comments

1
var input = 'n1=v1&n2=v2&n3=v3';
var tokens = input.split('&');
var hashTable = {};

for (var i = 0; i < tokens.length; i++) {
    var keyValuePair = tokens[i].split('=');
    var key = keyValuePair[0];
    var value = keyValuePair[1];

    hashTable[key] = value;
}

alert(JSON.stringify(hashTable));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.