JavaScript 将字符串拆分为 json
我想将字符串拆分为 JSON。下面是一些例子:
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
我希望我能从每一行获取 JSON:
[
{
day: Mon,
openning_time: 7:15 pm
closing_time: 3:30 am
},
....
]
我已经尝试了很多方法但仍然无法做到。希望能得到一些想法
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许这不是最佳性能解决方案,但您可以理解。
最后一部分丢失了,因为我不确定日期符号,所以我把它留给你。
基本上,您必须实现的是另一个平面图,它将日期字符串拆分为日期数组
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
我建议使用
String. split()
将每个输入字符串拆分为字段。完成后,我们将使用正则表达式将每个字段解析为日期、开放时间和关闭时间,使用
String.match()
。我们还创建一个
splitDays()
函数,将诸如Mon, Weds - Thurs
这样的日期范围转换为诸如[Mon,Weds,Thurs] 这样的日期数组]
,这将使我们能够创建最终结果。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 likeMon, Weds - Thurs
into an array of days like[Mon,Weds,Thurs]
, this will allow us to create the final result.