gpt4 book ai didi

javascript - 如何在 json 数组中定义重复的键?

转载 作者:行者123 更新时间:2023-12-03 00:50:27 24 4
gpt4 key购买 nike

我正在制作一个程序来解析 json 文件以获取 dnd 信息。我已经完成了该程序,但是,如果不手动给出数千个 key 的唯一 ID,我无法弄清楚如何为各种攻击定义重复的 key 。

我的 JSON 文件的一部分:

{
"special_abilities": [
{
"name": "Legendary Resistance (3/Day)",
"desc": "If the tarrasque fails a saving throw, it can choose to succeed instead.",
"attack_bonus": 0
},
{
"name": "Magic Resistance",
"desc": "The tarrasque has advantage on saving throws against spells and other magical effects.",
"attack_bonus": 0
},
{
"name": "Reflective Carapace",
"desc": "Any time the tarrasque is targeted by a magic missile spell, a line spell, or a spell that requires a ranged attack roll, roll a d6. On a 1 to 5, the tarrasque is unaffected. On a 6, the tarrasque is unaffected, and the effect is reflected back at the caster as though it originated from the tarrasque, turning the caster into the target.",
"attack_bonus": 0
},
{
"name": "Siege Monster",
"desc": "The tarrasque deals double damage to objects and structures.",
"attack_bonus": 0
}
]
}

那么,我将如何定义每个 name key ?如果我可以将我在那里发布的内容定义为 searchFile.special_abilities ,我如何定义searchFile.special_abilities.name

最佳答案

您的 JSON 有效。您可以像这样访问解析后的 JSON 数据:

const searchFile = JSON.parse(jsonVarName)

const index = 2 // or whatever index you want

const name = searchFile.special_abilities[index].name

您还可以使用各种array methods使用数据做各种有趣的事情,例如按名称搜索:

const siegeMonster = searchFile.special_abilities.find(ability => ability.name === 'Siege Monster')

关于javascript - 如何在 json 数组中定义重复的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53071209/

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