纯文本到JSON

我的应用程序按需启动AWS ElasticBeanstalk环境。 这些EB环境自动订阅AWS SNS主题,通过HTTP POST将消息发送到我的应用程序webhook URL。

问题是,下面是一个“消息”对象的例子,数据以纯文本的forms发送到webhook,所以在消息的任何地方都有\n实例,这对我来说是没有用的。 我希望在那里有一个新的对象,我的应用程序可以清楚地访问(通过Message.Timestamp,Message.Message等)

 Message: 'Timestamp: Fri Aug 21 22:25:23 UTC 2015\nMessage: Adding instance 'xxx' to your environment.\n\nEnvironment: xxx\nApplication: xxx\n\nEnvironment URL: xxx\nNotificationProcessId: xxx' 

那可能吗…?

当然可以 只需使用一些RegExp和一些.split()方法和BAM即可。

 var a = "Timestamp: Fri Aug 21 22:25:23 UTC 2015\nMessage: Adding instance 'xxx' to your environment.\n\nEnvironment: xxx\nApplication: xxx\n\nEnvironment URL: xxx\nNotificationProcessId: xxx"; // Break it up at the \n's var b = a.split(/\n+/); // I don't like using the same variable that I'm messing with, so let's make a new one. var Message = {}; // Loop through, break each string where the ": " is, and assign key: value to Message. b.forEach(function(str) { var data = str.split(/:\s/); // Get rid of whitespace in the object key. Message[data[0].replace(/\s/, "")] = data[1]; }); // See the results of each step. console.log(a, b, "Message:", Message); 

在你的例子中有\n和一些\n\n实例,所以这段代码将适应(或更多)。

现场演示