我有以下JSON:
{
"result": "success",
"json": {
"'1'-'V17511500523287'": [{
"hits": 1,
"sid": 1,
}]
}
}
我想把它变成:
{
"result": "success",
"json": [{
"hits": 1,
"sid": 1,
}],
"length": 1
}
意思是id喜欢删除"'1'-'V17511500523287'"
但保留内部内容。
这有可能吗?
答案 0 :(得分:0)
您可以使用Object.keys(...)获取结果中的键,然后使用它来获取您想要的内部内容。
这是一些实现这一目标的代码。如果您计划在其他地方执行此操作,请将其置于函数中。
var response = {
"result": "success",
"json": {
"'1'-'V17511500523287'": [{
"hits": 1,
"sid": 1,
}]
}
};
var response_keys = Object.keys(response.json);
response.length = response_keys.length;
if (response_keys.length == 1) {
response.json = response.json[response_keys[0]];
} else {
// you can drop that if you don't want to handle more than one key,
// or throw/return an error instead
var _tmp = [];
response_keys.forEach(function(key) {
_tmp.push(response.json[key]);
});
response.json = _tmp;
_tmp = undefined;
}
console.log(JSON.stringify(response, null, 2));
<强>输出:强>
{
"result": "success",
"json": [
{
"hits": 1,
"sid": 1
}
],
"length": 1
}