Use the variable in JSON.stringify

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

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

where result is the js object; I get the correct output for this:

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

but now I would like to use a variable instead of a fixed string on the left side of the stringify function; sort of:

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

this does not work because the name becomes a fixed string in a string object

+6
source share
3 answers

You need to create an object using indexer notation:

 var name = ...; var obj = {}; obj[name] = something; 
+13
source

You can use new for anonymous function:

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

If you want a JSON.stringify () Object, try the following:

 var field = "my_field_name"; var obj = {}; obj[field] = value; var myJSON = JSON.stringify(obj); 
0
source

All Articles