简体   繁体   English

使用 process.env 更改 Node.js 中 json object 的值

[英]Change the value of a json object in Node.js with process.env

I'm learning Node.js atm and am trying to change the response of an app request, depending on certain parameters.我正在学习 Node.js atm 并尝试根据某些参数更改应用程序请求的响应。 For instance if I set the MESSAGE_STYLE to uppercase I want the value of the (single) key in the json object to become uppercase.例如,如果我将 MESSAGE_STYLE 设置为大写,我希望 json object 中的(单个)键的值变为大写。 However I can't seem to change the object.但是我似乎无法更改 object。 I'm not reading the value as a string it seems, so to toUpperCase() doesn't work.我没有将值作为字符串读取,因此 toUpperCase() 不起作用。

After reading this article I tried JSON.parse and then JSON.dump but that didn't work either (unless I did it wrong).阅读这篇文章后,我尝试了 JSON.parse 和 JSON.dump ,但这也不起作用(除非我做错了)。 Help is much appreciated!非常感谢您的帮助!

THIS DOESN'T WORK这不起作用

process.env.MESSAGE_STYLE='uppercase';

app.get('/json', function(req, res){
var response = res.json({
  "message": "Hello json"
});

if(process.env.MESSAGE_STYLE==='uppercase'){
  response.message.toUpperCase();
  return response;
} else {
  return response;
  };
});

BUT THIS DOES但这确实

process.env.MESSAGE_STYLE='uppercase';

app.get('/json', function(req, res){

if(process.env.MESSAGE_STYLE==='uppercase'){
  res.json({
  "message": "HELLO JSON"
})
} else {
    res.json({
  "message": "Hello json"
})
  };
});

You have assigned the response object but it needs to be overridden to get your latest changes in response.message attribute.您已分配response object 但需要覆盖它以获取您对response.message属性的最新更改。

process.env.MESSAGE_STYLE='uppercase';

app.get('/json', function(req, res){
// Variable assignment as object
var response = {
  "message": "Hello json"
};

if(process.env.MESSAGE_STYLE==='uppercase'){
  //Override message attribute value based on condition
  response.message = response.message.toUpperCase();  
}

return res.json(response);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM