gpt4 book ai didi

javascript - 如何使用嵌套 json 中的键制作另一个嵌套 json

转载 作者:行者123 更新时间:2023-11-29 17:52:13 24 4
gpt4 key购买 nike

来自源的字符串来自 JSON 对象中的碎片化 JSON 对象。我想将此 JSON 结构转换为另一个简单的 JSON 结构:

{  
"nestA":{
"a":"link",
"b":2711
},
"nestB":{
"a":"img",
"b":4165
}
}

能不能改成这样

 {  
"key":"nestA"
"a":"link"
"b":711
},
{
"key":"nestB"
"a":"img"
"b":165
}

最佳答案

//convert json string into an object
var json = '{"nestA":{"a":"link","b":2711},"nestB":{"a":"img","b":4165}}'
var sourceObject = JSON.parse(json);

//get a list of the object keys
var keys = Object.keys(sourceObject);

//create a new array to hold our output
var array = [];

//loop through our keys adding them to our array in the format we want
keys.forEach(function(key){
var nest = sourceObject[key];
nest.key = key;
array.push(nest);
});

//convert our array back to json
var result = JSON.stringify(array);
console.log(result);

关于javascript - 如何使用嵌套 json 中的键制作另一个嵌套 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42427023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com