所以我有一个Nodejs服务器,它接收一个JSON对象,然后将它放入变量并通过电子邮件发送内容。这是我的代码:
app.post('/sendEmail', function(req, res) {
var answers = req.body.answers;
var str = JSON.stringify(answers, null, "\t"); // stringify with tabs inserted at each level
console.log(answers);
var fromEmail = new helper.Email('ahun...ok.com');
var toEmail = new helper.Email('ahun...ok.com');
var subject = 'Survey Completion';
var content = new helper.Content('text/plain', str);
var mail = new helper.Mail(fromEmail, subject, toEmail, content);
var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON()
});
sg.API(request, function (error, response) {
if (error) {
console.log('Error response received');
}
});
res.send("Success");
});

正如您所看到的,我使用stringify使JSON更漂亮,但它仍然具有所有粗括号和引号以及间距作为JSON。有没有办法以更易读的形式存储JSON?
电子邮件内容如下:
var content = new helper.Content('text/plain', str);
因此,可读的JSON需要存储在具有格式等的变量中。
任何帮助将不胜感激。感谢
编辑:这是发送的JSON对象:
{
"question1": {
"Reliable": true,
"Knowledgeable": true,
"Helpful": true,
"Courteous": true
},
"question2": {
"checked": "Extremely Well"
},
"question3": {
"checked": "Extremely Well"
},
"question4": {
"checked": 3
},
"fullName": "Test",
"address": "Test",
"city": "Test",
"state": "Test",
"zip": "321",
"areaCode": "321",
"phone": 1234567896,
"call": true,
"lifeInsurance": "Yes",
"brokerage": "Yes",
"bankName": "Regions"
}

使用上面的JSON对象,我想将其格式化为:
问题1:可靠,知识渊博,乐于助人,彬彬有礼。
问题2:非常好。
问题3:非常好。
问题4:3。
全名:测试。
地址:测试。
...
经纪:是的。
银行名称:地区。
答案 0 :(得分:1)
数据只需要一点按摩
var data = {
"question1": {
"Reliable": true,
"Knowledgeable": false,
"Helpful": true,
"Courteous": true
},
"question2": {
"checked": "Extremely Well"
},
"question3": {
"checked": "Extremely Well"
},
"question4": {
"checked": 3
},
"fullName": "Test",
"address": "Test",
"city": "Test",
"state": "Test",
"zip": "321",
"areaCode": "321",
"phone": 1234567896,
"call": true,
"lifeInsurance": "Yes",
"brokerage": "Yes",
"bankName": "Regions"
};
var result = Object.entries(data).reduce((result, [key, value]) => {
key = key.replace(/([A-Z]|\d+)/g, ' $1').replace(/^(.)/, (unused, p1) => p1.toUpperCase());
if (!['string', 'number', 'boolean'].includes(typeof value)) {
value = Object.entries(value).map(([key, value]) => (typeof value == 'boolean') ? (value ? key : undefined) : value).filter(v => v !== undefined).join(',');
}
result.push(`${key}: ${value}`);
return result;
}, []);
console.log(result.join('\n'));

注意:我将其中一个true更改为false以检查逻辑
在节点8.1.2中测试
答案 1 :(得分:0)
更简单的答案可能是解析JSON然后将其转储为YAML:
---
question1:
Reliable: true
Knowledgeable: true
Helpful: true
Courteous: true
question2:
checked: Extremely Well
question3:
checked: Extremely Well
question4:
checked: 3
fullName: Test
address: Test
city: Test
state: Test
zip: '321'
areaCode: '321'
phone: 1234567896
call: true
lifeInsurance: 'Yes'
brokerage: 'Yes'
bankName: Regions
Node.js有几个YAML库,我不记得我喜欢哪个,但我想说我在js-yaml上运气不错。