admin管理员组

文章数量:1206979

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!

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!

Share Improve this question edited Jan 30, 2012 at 12:53 Alexander Abramovich asked Jan 30, 2012 at 12:48 Alexander AbramovichAlexander Abramovich 11.4k26 gold badges74 silver badges113 bronze badges 2
  • possible duplicate of How can I convert query string or JSON object map to single JSON object with jQuery? – mplungjan 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. – Tim Down Commented Jan 30, 2012 at 13:05
Add a comment  | 

10 Answers 10

Reset to default 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

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

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', ';')
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];
}

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
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, '"},{"') + '"}]')

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

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.

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

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

本文标签: javascriptHow to parse a string into a hashtableStack Overflow