Home > Software engineering >  JavaScript split string into json
JavaScript split string into json

Time:04-01

I would like to split the string into JSON. Below is some example:

Mon, Fri 2:30 pm - 8 pm / Tues 15 am - 2 pm / Weds 1:15 pm - 3:15 am /....

Mon, Weds - Thurs, Sat 7:15 pm - 3:30 am / Tues 4:45 pm - 5 pm / Fri 8:25 am - 9:30 pm / ...

Mon, Weds - Sun 7:15 pm - 3:30 am

Mon - Sun 7:15 pm - 3:30 am

I hope I can get the JSON from each line:

[
    {
        day: Mon,
        openning_time: 7:15 pm
        closing_time: 3:30 am
    },
    ....
]

I had tried many methods but still cannot make it. Hope can get some idea

CodePudding user response:

Before split, make a regular expression (regex). On the basic of regex you have to split this string expression and convert this into array. Then json encode this array

CodePudding user response:

Probably this is not a best performance solution but you can get the idea. The last part is missing because I'm not sure of the day notation so I leave that to you. Basically what you have to implement is another flatmap that splits the day string in an array of days

const stringToParse = 
`Mon, Fri 2:30 pm - 8 pm / Tues 15 am - 2 pm / Weds 1:15 pm - 3:15 am
Mon, Weds - Thurs, Sat 7:15 pm - 3:30 am / Tues 4:45 pm - 5 pm / Fri 8:25 am - 9:30 pm
Mon, Weds - Sun 7:15 pm - 3:30 am
Mon - Sun 7:15 pm - 3:30 am`;

const daysArray = ['Mon', 'Tues', 'Weds', 'Thurs', 'Fri', 'Sat', 'Sun']

const json = stringToParse.split('\n')
.flatMap(line => line.split('/').map(s => s.trim()))
.map(s => {
  const [closingType, closing, _,openingType, opening, ...days] = s.split(' ').reverse()
  return {
    days: days.reverse().join(' '),
    openning_time: `${opening} ${openingType}`,
    closing_time: `${closing} ${closingType}`
  }
})

console.log(json)

CodePudding user response:

Suppose the format is fixed, just split & split...

const weekdays = ['Mon', 'Tues', 'Weds', 'Thurs', 'Fri', 'Sat', 'Sun'];
const split = (str) => str.split('/').flatMap(part => {
  const tokens = part.split(new RegExp('('   weekdays.join('|')   ')')).map(token => token.trim()).filter(token => token !== '' && token !== ',').flatMap((token, index, arr) => {
    if (token === '-') {
      const f = weekdays.findIndex(w => w === arr[index - 1]);
      const t = weekdays.findIndex(w => w === arr[index   1]);
      return weekdays.slice(f   1, t);
    } else {
      return [token];
    }
  });
  const [openning_time, closing_time] = tokens.pop().split('-').map(t => t.trim());
  return tokens.map(day => ({
    day,
    openning_time,
    closing_time
  }));
});

console.log(split('Mon, Fri 2:30 pm - 8 pm / Tues 15 am - 2 pm / Weds 1:15 pm - 3:15 am'));
console.log(split('Mon, Weds - Thurs, Sat 7:15 pm - 3:30 am / Tues 4:45 pm - 5 pm / Fri 8:25 am - 9:30 pm'));
console.log(split('Mon, Weds - Sun 7:15 pm - 3:30 am'));
console.log(split('Mon - Sun 7:15 pm - 3:30 am'));

CodePudding user response:

I'd suggest using String.split() to split each input string into fields.

Once this is complete we'll use a regular expression to parse each field into day, opening time and closing time using String.match().

We'd also create a splitDays() function to turn a day range like Mon, Weds - Thurs into an array of days like [Mon,Weds,Thurs], this will allow us to create the final result.

function splitDays(days) {
    return days.split(',').flatMap(splitDayRange);  
}

function splitDayRange(range) {
    const days = ['Mon', 'Tues', 'Weds', 'Thurs', 'Fri', 'Sat', 'Sun'];
    const [startIndex, endIndex] = range.trim().split(/\s*\-\s*/).map(day => days.findIndex(d => d === day));
    return days.filter((day, idx, arr) => { 
        return (idx >= startIndex) && (idx <= (endIndex || startIndex));
    });
}

function parseInput(input) {
    const parseRegEx = /([a-z\s\,\-]*)(\d :?\d* (?:am|pm))\s*\-\s*(\d :?\d*\s*(am|pm))/i
    return input.split(/\s*\/\s*/).flatMap(field => { 
        const [, days, opening_time, closing_time ] = field.match(parseRegEx);
        return splitDays(days).map(day => { 
            return { day, opening_time, closing_time };
        })
    });
}

let inputs = [
    'Mon, Fri 2:30 pm - 8 pm / Tues 15 am - 2 pm / Weds 1:15 pm - 3:15 am',
    'Mon, Weds - Thurs, Sat 7:15 pm - 3:30 am / Tues 4:45 pm - 5 pm / Fri 8:25 am - 9:30 pm',
    'Mon, Weds - Sun 7:15 pm - 3:30 am',
    'Mon - Sun 7:15 pm - 3:30 am'
]

for(let input of inputs) {
    console.log('Input:');
    console.log(input);
    console.log('Output:');
    console.log(parseInput(input));
} 
.as-console-wrapper { max-height: 100% !important; }

  • Related