Lingbo Tang Lingbo Tang - 4 months ago 8
JSON Question

Cleaner solution to parse message and return json

I'm writing a function to subscribe data transmitting through bluetooth and parse it, finally return specific info into output json.

My message format will be 'Header','Id','Ggid','Ppayload','Ttimestamp','AsigA','BsigB'. In this format, there's no space between each segment but one comma. Only Id and Header are necessary in this format. Header is static, and will always start with an 'H'. Other info will start with a capital letter except 'Id'. For example, Id segment can be 12345678, but payload segment will be P12345678. Currently, I'm having a really complicated code to parse this info.

Example Message is a string: H,00198601,GLOCATE,P762,T1.50,A64,B67

var len = Message.length;
app.outputTagJson.Tag = {};
if (len >= 2)
{
app.outputTagJson.Tag.tagID = Message[1];
app.outputTagJson.Tag.isLost = "False";
if (len >= 3)
{
app.outputTagJson.Tag.groupID = Message[2].slice(1,Message[2].length);
if (len >= 4)
{
app.outputTagJson.Tag.payload = Message[3].slice(1,Message[3].length);
if (len >= 5)
{
app.outputTagJson.Tag.timeStamp = Message[4].slice(1,Message[4].length);
if (len >= 6)
{
app.outputTagJson.Tag.sigStrenthA = Message[5].slice(1,Message[5].length);
if (len >= 7)
{
app.outputTagJson.Tag.sigStrenthB = Message[6].slice(1,Message[6].length);
}
}
}
}
}
}


I'm thinking a generic regular expression to cut this format in javascript, but I'm not farmiliar with it. So is there any cleaner solution without using regular expression or if I have to use regular expression, how can I approach that?

Answer

Give this a try?

var input = 'H,00198601,GLOCATE,P762,T1.50,A64,B67';

var fieldMap = {
    G: 'groupID',
    P: 'payload',
    T: 'timeStamp',
    A: 'sigStrengthA', // NOTE: you misspelled "strength"
    B: 'sigStrengthB',
};

var fields = input.split(',');
var tag = {};

tag.tagID = fields[1];

fields.slice(2).forEach(function (field) {
    tag[fieldMap[field[0]]] = field.substring(1);
});

console.log(JSON.stringify(tag, null, 4));

// Output:
// {
//     "tagID": "00198601",
//     "groupID": "LOCATE",
//     "payload": "762",
//     "timeStamp": "1.50",
//     "sigStrengthA": "64",
//     "sigStrengthB": "67"
// }

EDIT

Another solution that relies purely on field order (now that I see the fields are always in the same order):

var input = 'H,00198601,GLOCATE,P762,T1.50,A64,B67';

var fieldNames = [
    'tagID',
    'groupID',
    'payload',
    'timeStamp',
    'sigStrengthA',
    'sigStrengthB',
];

var tag = {};
var fields = input.split(',');
for (var i = 1; i < fields.length; i++) {
    tag[fieldNames[i-1]] = fields[i].substring(i === 1 ? 0 : 1);
}

console.log(JSON.stringify(tag, null, 4));

// Output:
// {
//     "tagID": "00198601",
//     "groupID": "LOCATE",
//     "payload": "762",
//     "timeStamp": "1.50",
//     "sigStrengthA": "64",
//     "sigStrengthB": "67"
// }