Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build a JSON string from a JSON object [duplicate]

Tags:

json

jquery

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"}]
like image 669
NaN Avatar asked Oct 02 '22 10:10

NaN


1 Answers

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 );
like image 68
Sirko Avatar answered Oct 07 '22 20:10

Sirko