Search code examples
jsonxmlxqueryoxygenxml

XQuery how to count all the "spells" in JSON


I have the following JSON file:

"spells": [
 {
  "spell":"Aberto",
  "effect":"opens objects",
  "_id":"5b74ebd5fb6fc0739646754c",
  "type":"Charm"
 },
 {
  "spell":"Accio",
  "effect":"Summons an object",
  "__v":0,
  "_id":"5b74ecfa3228320021ab622b",
  "type":"Charm"
 },
 {
  "spell":"Age Line",
  "effect":"Hides things from younger people",
  "__v":0,
  "_id":"5b74ed2f3228320021ab622c",
  "type":"Enchantment"
 },
 {
  "spell":"Aguamenti",
  "effect":"shoots water from wand",
  "__v":0,
  "_id":"5b74ed453228320021ab622d",
  "type":"Charm"
 },
 {
  "spell":"Alarte Ascendare",
  "effect":"shoots things high in the air",
  "__v":0,
  "_id":"5b74ed583228320021ab622e",
  "type":"Spell"
 }

}

Can you help me how to count all the spells with XQuery where the "type" = "Spell" and separately all the spells where the "Type"= "charm". The JSON file is much bigger, I just don't wanted to paste here the whole file. Thank you.


Solution

  • It seems like a straight-forward grouping and counting then:

    declare variable $spell-types as xs:string* external := ('Spell', 'Charm');
    
    for $spell in ?spells?*[?type = $spell-types]
    group by $t := $spell?type
    return $t || ' : ' || count($spell)
    

    https://xqueryfiddle.liberty-development.net/nc4P6y2

    Or, as Michael Kay has pointed out, with a given sequence of values it suffices to use

    for $spell-type in $spell-types
    return $spell-type || ' : ' || count(?spells?*[?type = $spell-type])
    

    https://xqueryfiddle.liberty-development.net/nc4P6y2/1