我正在制作一个解析json文件以获得dnd信息的程序。我已经完成了该程序,但是,如果不手动提供数千个唯一的ID,就无法弄清楚如何为各种攻击定义重复的密钥。
我的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
键?
如果我可以定义在那里发布的内容为searchFile.special_abilities
,该如何定义searchFile.special_abilities.name
?
答案 0 :(得分:1)
您的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')
答案 1 :(得分:0)
我建议改用数组对象,按名称索引,这样就不会重复名称,也不需要单独的唯一标识符。例如:
"special_abilities": {
"Some Name": [
{
"desc": "Description 1",
"attack_bonus": 0
},
{
"desc": "Description 2",
"attack_bonus": 5
}
],
"Some Other Name": [
{
"desc": "Some Other Description",
"attack_bonus": 2
}
]
}
然后,您可以访问special_abilities['Some name']
来访问数组,并遍历数组以查找所需的内容。 (使用Object.entries
一次获取键和值,例如Object.entries(special_abilities).forEach(([name, arr]) => { ...
)