简体   繁体   中英

How Do I Parse a Pipe-Delimited String into Key-Value Pairs in Javascript

I want to parse the following sort of string into key-value pairs in a Javascript object:

var stringVar = 'PLNC||0|EOR|<br>SUBD|Pines|1|EOR|<br>CITY|Fort Myers|1|EOR|<br>';

Each word of 4 capital letters (PLNC, SUBD, and CITY) is to be a key, while the word(s) in the immediately following pipe are to be the value (the first one, for PLNC, would be undefined, the one for SUBD would be 'Pines', the one for CITY would be 'Fort Myers').

Note that '|EOR|
' immediately precedes every key-value pair.

What is the best way of doing this?

I just realised it's technically a csv format with interesting line endings. There are limitations to this in that your variable values cannot contain any | or < br> since they are the tokens which define the structure of the string. You could of course escape them.

var stringVar = 'PLNC||0|EOR|<br>SUBD|Pines|1|EOR|<br>CITY|Fort Myers|1|EOR|<br>';

function decodeString(str, variable_sep, line_endings)
{
    var result = [];
    var lines = str.split(line_endings);
    for (var i=0; i<lines.length; i++) {
        var line = lines[i];
        var variables = line.split(variable_sep);
        if (variables.length > 1) {
            result[variables[0]] = variables[1];
        }
    }
    return result;
}

var result = decodeString(stringVar, "|", "<br>");

console.log(result);

If you have underscore (and if you don't, then just try this out by opening up your console on their webpage, because they've got underscore included :)

then play around with it a bit. Here's a start for your journey:

_.compact(stringVar.split(/<br>|EOR|\|/))

Try

function parse(str) {
    var str = str.replace(/<br>/gi);
    console.log(str);
    var arr = str.split('|');
    var obj = {};
    for (var i=0; i<arr.length; i=i+4) {
        var key = arr[i] || '';
        var val_1 = arr[i+1] || '';
        var val_2 = arr[i+2] || '';
        if(key) {
            obj[key] = val_1 + ':' + val_2; //or similar
        }
    }
    return obj;
}

DEMO

This will work on the particular data string in the question.

It will also work on other data string of the same general format, but relies on :

  • <br> being discardable before parsing
  • every record being a group of 4 string elements delineated by | (pipe)
  • first element of each record is the key
  • second and third elements combine to form the value
  • fourth element is discardable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM