Here is the input that should be converted to JSON format as given below.
{RS0004036}:{0;3}:{0000003AB;0000003BC}_{RS0004036}:{3;3}:{0000003DE;0000003FG}_{RS0004036}:{1;2}:{0000003HI;0000003JK}
The code should read the above input, will create a JSON return string as follows. The returning JSON will return store which will be only one value of the index 0 of the input string and will not repeat as partList
. Target JSON should be like this.
"storeList": [
{
"store": "RS0004036",
"partList": [
{
"part": "0000003AB",
"partSub": "0000003BC",
"qtyOnHand": "0",
"qtyMinMax": "3"
},
{
"part": "0000003DE",
"partSub": "0000003FG",
"qtyOnHand": "3",
"qtyMinMax": "3"
},
{
"part": "0000003HI",
"partSub": "0000003JK",
"qtyOnHand": "1",
"qtyMinMax": "2"
}
]
}
]
Here is my code:
const hdr_str = '{RS0004036}:{1;2}:{0000003AB;0000003BC}_{RS0004036}:{0;3}:{0000003DE;0000003FG}_{RS0004036}:{3;3}:{0000003HI;0000003JK}';;
var storeList = {};
var partList = [];
storeList.partList = partList;
//Processing
const partsDataEntries = hdr_str.split('_');
for (var index = 0; index < partsDataEntries.length; index++) {
const element = partsDataEntries[index].slice(1, -1);
console.log('element0' + element);
if (element != '') {
const storepart = element.split(':');
const storeId = storepart[0].slice(1, -1);
const [qtyOnHand, qtyMinMax] = element.split(':')[1].split(';');
console.log("element.split(':')[1]" + element.split(':')[1]);
const qtyOH = qtyOnHand.substring(1, qtyOnHand.length);
const qtyMM = qtyMinMax.substring(0, qtyMinMax.length - 1);
const [partnum, partsub] = element.split(':')[2].split(';');
const part = partnum.substring(1, partnum.length);
storeList.storeId = storeId;
partList = {
"partnum": part,
"partsub": partsub,
"qtyOnHand": qtyOH,
"qtyMinMax": qtyMM
}
storeList.partList.push(partList);
}
}
console.log(JSON.stringify(storeList));
Somehow it is repeating the elements in my tool which has JavaScript engine which is very old and we cannot replace the tool. Can someone suggest how to fix it?
{"partList":[{"partnum":"0000003AB","partsub":"0000003BC","qtyOnHand":"0","qtyMinMax":"3"}{"partnum":"0000003AB","partsub":"0000003BC","qtyOnHand":"0","qtyMinMax":"3"},{"partnum":"0000003AB","partsub":"0000003BC","qtyOnHand":"0","qtyMinMax":"3"}],"storeId":"RS0004036"}
2
Answers
You could match and get all information to the reqired variables/properties.
Rather than use string split/slice, use named capturing groups in a regular expression, eg:
You can use this to parse each element and get the relevant property from the capturing groups result, eg
Updated snippet that extracts each part List and combines into a store list: