javascript 在 JSON.stringify 中使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21708652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:31:00  来源:igfitidea点击:

use a variable in JSON.stringify

javascriptjsonnode.jsstringify

提问by Cereal Killer

I use stringify in my node restful server to provide data:

我在节点 restful 服务器中使用 stringify 来提供数据:

answer = JSON.stringify({activities: result}, null, '\t');
return answer

where result is a js object; i receive the correct output for this:

其中 result 是一个 js 对象;我收到了正确的输出:

{
"activities": [
    {
     "id": 1,
     "title": aaa
    },
    { 
     "id": 2,
     "title": bbb
    }
  ]
}

but now i would like to use a variable instead of a fixed string in the left part of stringify function; something like:

但现在我想在 stringify 函数的左侧使用变量而不是固定字符串;就像是:

var name = "activities";
answer = JSON.stringify({name: result}, null, '\t');

this doesn't work, because name becomes a fixed string in the stringified object

这不起作用,因为 name 成为字符串化对象中的固定字符串

回答by SLaks

You need to build an object using indexer notation:

您需要使用索引器符号构建一个对象:

var name = ...;
var obj = {};
obj[name] = something;

回答by Paul

You can use newwith an anonymous function to do it as well:

您也可以使用new匿名函数来执行此操作:

answer = JSON.stringify(new function(){ this[name] = result; }, null, '\t');

回答by Satish

If you want JSON.stringify() Object then try this:

如果你想要 JSON.stringify() 对象,那么试试这个:

var field = "my_field_name";

var obj = {};

obj[field] = value;

var myJSON = JSON.stringify(obj);