如何从JSON对象构建JSON字符串

NaN*_*NaN 5 jquery json

我试图获取一个JSON对象并构建一个JSON字符串,但我不知道该怎么做.

这是我到目前为止给出的正确输出.

var execs = '';
$.each(window.ob.executives, function(idx, obj) {
    execs = idx + ':' + obj.name;
});
Run Code Online (Sandbox Code Playgroud)

我需要的是这样的字符串:

{ 1: 'test1', 2: 'test2', 3: 'test3', 4: 'test4' }
Run Code Online (Sandbox Code Playgroud)

有人能告诉我如何构建这个字符串吗?

此外,您可能会注意到我使用的window变量我理解不好.如果有人可以告诉我如何获取此变量的内容,这是另一个函数,那将非常感激.

编辑: stringify不会给我我需要的东西.这是我得到的:

[{"test1":"1","test2":"2"},{"test3":"3","test4":"4"}]
Run Code Online (Sandbox Code Playgroud)

Sir*_*rko 4

这里不需要 jQuery:

var execs = JSON.stringify( window.ob.executives );
Run Code Online (Sandbox Code Playgroud)

编辑

在OP指定变量的结构之后,我建议如下(遍历两层嵌套对象,提取数据将其添加到中间对象,然后可以序列化):

var obj = {};
$.each(window.ob.executives, function( key, val ) {
  $.each( val, function( iKey, iVal ) {
    obj[ iVal ] = iKey;
  });
});
var execs = JSON.stringify( obj );
Run Code Online (Sandbox Code Playgroud)