0

I am making a program that parses json files for dnd information. I have completed the program, however, I cannot figure out how to define the duplicate keys for the various attacks without manually giving thousands of keys unique ids.

Part of my JSON file:

{
  "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
    }
  ]
}

So, how would I define each of the name keys? If I can define what I posted up there as searchFile.special_abilities, how would I define searchFile.special_abilities.name?

Tobyhn
  • 380
  • 2
  • 5
  • 17

2 Answers2

1

Your JSON is valid. You would access the parsed JSON data like so:

const searchFile = JSON.parse(jsonVarName)

const index = 2 // or whatever index you want

const name = searchFile.special_abilities[index].name

You can also use the various array methods to do all sorts of interesting things with the data, like searching by name:

const siegeMonster = searchFile.special_abilities.find(ability => ability.name === 'Siege Monster')
Ben Steward
  • 2,338
  • 1
  • 13
  • 23
0

I'd suggest using a object of arrays instead, indexed by name, that way the name is never duplicated, and there's no need for separate unique identifiers. For example:

"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
    }
  ]
}

Then, you could access special_abilities['Some name'] to get to the array, and iterate over the array to find what you're looking for. (Use Object.entries to get both the key and the value at once, eg Object.entries(special_abilities).forEach(([name, arr]) => { ... )

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • The problem with this, it that I would have to manually implement it for thousands of other monsters in the json file as well. – Tobyhn Oct 30 '18 at 19:12