假设我有一个像这样的数组:
{
MNC:
[
{
instanceId: 'i-0c025b0755f5e3e5d6',
systemId: 'NWD',
instanceState: 'running',
tags: [Array],
env_type: 'DB_CI_APP'
}
]
}
我想将上述数组以JSON格式打印为
{
"key": "MNC",
"value":
[
{
"instanceId": "i-0c025b0755f5e3e5d6"
}
]
}
答案 0 :(得分:0)
在JavaScript中,您可以使用JSON.stringify
将数组或值转换为JSON格式的字符串。
var x = [{'a': 'b'}];
var b = JSON.stringify(x);
var c = b.substring(1, b.length - 1);
JSON.parse(c);
console.log(c);
答案 1 :(得分:0)
您可以通过以下方式做到这一点:
var obj =
{
MNC:
[
{
instanceId: 'i-0c025b0755f5e3e5d6',
systemId: 'NWD',
instanceState: 'running',
tags: [Array],
env_type: 'DB_CI_APP'
}
]
};
var newObj = {};
for(var key in obj)
{
newObj['key'] = key;
break;
}
newObj.value = obj[newObj['key']];
delete newObj.value[0].systemId;
delete newObj.value[0].instanceState;
delete newObj.value[0].tags;
delete newObj.value[0].env_type;
var yourJSONstr = JSON.stringify(newObj, null, 4);
console.log(yourJSONstr);
或者您也可以通过以下方式做到这一点:
var obj =
{
MNC:
[
{
instanceId: 'i-0c025b0755f5e3e5d6',
systemId: 'NWD',
instanceState: 'running',
tags: [Array],
env_type: 'DB_CI_APP'
}
]
};
var newObj = {key: 'MNC', value: obj.MNC};
delete newObj.value[0].systemId;
delete newObj.value[0].instanceState;
delete newObj.value[0].tags;
delete newObj.value[0].env_type;
var yourJSONstr = JSON.stringify(newObj, null, 4);
console.log(yourJSONstr);