我如何在json对象中获得所有第二个选择的所有名称部分



这是我想要获取内容的完整对象:

{
"name": "permissions",
"description": "Get or edit permissions for a user or a role",
"options": [
{
"name": "user",
"description": "Get or edit permissions for a user",
"type": 2, 
"options": [
{
"name": "get",
"description": "Get permissions for a user",
"type": 1, 
"options": [
{
"name": "user",
"description": "The user to get",
"type": 6,
"required": true
},
{
"name": "channel",
"description": "The channel permissions to get. If omitted, the guild permissions will be returned",
"type": 7,
"required": false
}
]
},
{
"name": "edit",
"description": "Edit permissions for a user",
"type": 1,
"options": [
{
"name": "user",
"description": "The user to edit",
"type": 6,
"required": true
},
{
"name": "channel",
"description": "The channel permissions to edit. If omitted, the guild permissions will be edited",
"type": 7,
"required": false
}
]
}
]
},
{
"name": "role",
"description": "Get or edit permissions for a role",
"type": 2,
"options": [
{
"name": "get",
"description": "Get permissions for a role",
"type": 1,
"options": [
{
"name": "role",
"description": "The role to get",
"type": 8, 
"required": true
},
{
"name": "channel",
"description": "The channel permissions to get. If omitted, the guild permissions will be returned",
"type": 7,
"required": false
}
]
},
{
"name": "edit",
"description": "Edit permissions for a role",
"type": 1,
"options": [
{
"name": "role",
"description": "The role to edit",
"type": 8,
"required": true
},
{
"name": "channel",
"description": "The channel permissions to edit. If omitted, the guild permissions will be edited",
"type": 7,
"required": false
}
]
}
]
}
]
}

我想从第一个json对象中获得所有这些名称属性,并将它们全部分配给javascript中的不同变量?我怎样才能做到这一点呢?

权限——比;作用——比;编辑——比;通道(换句话说,我想获得json对象中所有第二个选项中的所有名称部分)

如果你知道JSON结构是固定的,那么它将很容易。

考虑你的json被分配给permissionJson,那么你可以把它写为

permissionJson.name  // permissions
permissionJson.options[1].name. // role
permissionJson.options[1].options[1].name // edit
permissionJson.options[1].options[1].options[1].name // channel

如果JSON结构是动态的,那么你可能需要循环来提取每个级别的选项数组索引1元素并找到它的名称。

首先我想说清楚,我不是很明白你的问题。所以如果我误解了什么,请纠正我。您说要在选项(根数组)的所有第二个成员中获取所有名称部分。所以你要做的就是

JSON_DATA.options[1]

在这里您选择了整个role对象。要更深入,可以使用点运算符。For instance Permissions——>作用——比;编辑——比;通道。这可以通过JSON_DATA.options[1].options[1]这行来访问它将返回这个

{
"name": "channel",
"description": "The channel permissions to get. If omitted, the guild permissions will be returned",
"type": 7,
"required": false
}

此解决方案适用于对象将来可能达到的深度

这是您的解决方案:只需使用这个函数,并创建变量allSecondNames:

const allSecondNames = [];
func = a => {
if (a.name) allSecondNames.push(a.name);
if (a.options) func(a.options)
if (a[1] && a[1].name) allSecondNames.push(a[1].name); 
if (a[1]?.options) func(a[1].options)
}

将JSON发送到函数func将放入变量allSecondNames:

["permissions", "role", "edit", "channel"]

最新更新