I am trying to take a JSON object and build a JSON string but I'm not sure how to do it.
This is what I have so far that is giving me the correct output.
var execs = '';
$.each(window.ob.executives, function(idx, obj) {
execs = idx + ':' + obj.name;
});
What I need is a string like this:
{ 1: 'test1', 2: 'test2', 3: 'test3', 4: 'test4' }
Can someone show me how to build this string?
Also, you'll probably notice that I am using a window
variable which I understand isn't good. If someone can tell me how to get the contents of this variable, which is in another function, that would be greatly appreciated.
EDIT: stringify won't give me what I need guys. Here is what I get with that:
[{"test1":"1","test2":"2"},{"test3":"3","test4":"4"}]
No need for jQuery here:
var execs = JSON.stringify( window.ob.executives );
Edit
After OP specifying the structure of the variable, I suggest the following (Traversing through two levels of nested objects, extracting the data to add it to an intermediate object, which can then be serialized):
var obj = {};
$.each(window.ob.executives, function( key, val ) {
$.each( val, function( iKey, iVal ) {
obj[ iVal ] = iKey;
});
});
var execs = JSON.stringify( obj );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With