Converting formatted string to JSON object
I need help with parsing a specific string format in JavaScript. I have a string that contains employee data separated by special characters and I want to turn it into a proper JSON structure.
My input string looks like this:
employeeData = "#203|John|Doe|Engineer|45000|Basketball #204|Sarah|Johnson|Designer|52000|Tennis"
What I want to achieve:
[
{
"employeeId": "203",
"firstName": "John",
"surname": "Doe",
"position": "Engineer",
"income": "45000",
"hobby": "Basketball"
},
{
"employeeId": "204",
"firstName": "Sarah",
"surname": "Johnson",
"position": "Designer",
"income": "52000",
"hobby": "Tennis"
}
]
I tried using employeeData.split('#') but this gives me an array where each element still has the pipe symbols. I cannot figure out how to handle the nested separation properly. What would be the best approach to parse this kind of formatted string?
You can solve this with regex - it handles dual delimiters way better than multiple splits. Use employeeData.match(/#[^#]+/g) to grab each employee record first, then deal with the pipes. This regex grabs everything from # until it hits the next #. Once you’ve got the records, just strip the leading # with substring(1) and split on pipes. I’ve found this approach way less error-prone because it naturally handles edge cases where your string starts with a delimiter. Plus regex makes it super easy to validate the data format upfront - you can check if the pattern matches what you expect before processing anything.
just split by # first, then loop through each piece and split by | again. way more readable than regex and you can easily add validation if you need it. something like: for(let i=1; i<parts.length; i++) { let fields = parts[i].split(‘|’); // build your object here }
I’ve encountered this same parsing issue before. Chaining split operations works effectively for nested delimiters like this. Start by splitting on ‘#’ first, ensuring to filter out any empty elements (your string begins with ‘#’). After that, split each resulting piece on the pipe character. Here’s a viable approach: const result = employeeData.split(‘#’).filter(item => item.length > 0).map(employee => { const fields = employee.split(‘|’); return { employeeId: fields[0], firstName: fields[1], surname: fields[2], position: fields[3], income: fields[4], hobby: fields[5] }; }); The filter step eliminates the empty string before the first ‘#’, while the map function converts each employee string into an object by splitting it on pipes and assigning fields to their respective properties.