我有来自API的以下JSON响应。
{
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
}
语言我用来解析这个JSON:Javascript
框架:ReactNative
我如何解析它(注意:在我解析之前,我不知道蛋糕中id的值)?
PS:框架新手。非常感谢。
答案 0 :(得分:0)
我不确定,但我想你想以某种方式访问id为{e {x}的cake
。 7689
不知道其id
值。所以你有几种方法来处理它。其中之一是使用for...in
循环迭代它们:
for(var cakeId in response.cakes){
var cake = response.cakes[cakeId];
console.log(cake);
// Do whatever you want with your cake
}
如果我误解了你,我很抱歉。如果是这样,请通过向我们提供您希望实现的一些示例来澄清问题。
答案 1 :(得分:0)
创建函数
function getCake(obj,key){
let cake = obj['cakes'][key];
return cake;
}
致电
let cakes = {
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
}
getCake(cakes,'7689');
答案 2 :(得分:0)
尝试一下
const cakesObject = {
"status": true,
"cakes": {
"7689": {
"id": 7689,
"flavor": "chocolate",
"cookDetails": {
"id": 101,
"firstName": "Name1",
"lastName": "LastName1"
}
},
"7690": {
"id": 7690,
"flavor": "vanilla",
"cookDetails": {
"id": 102,
"firstName": "Name2",
"lastName": "LastName2"
}
}
}
};
// this is required only if cakesObject is strigified
const { cakes } = JSON.parse(cakesObject);
const cakesArray = [..Object.values(cakes)];
cakesArray.forEach(cake => {
const { id } = cake;
// write further logic
})