title: how to parse json with field of optional and variant type in Haskell?
body: <p>How I can parse the input json inside this file ? <a href="https://github.com/smogon/pokemon-showdown/blob/master/data/moves.js" rel="nofollow noreferrer">https://github.com/smogon/pokemon-showdown/blob/master/data/moves.js</a></p>
  <p>For the secondary and flags properties? They are optional and contains variant type.</p>
  <p>A minimal example would be this one:</p>
  <pre><code>[
    {},
    {
      &quot;secondary&quot;: false
    },
    {
  
      &quot;secondary&quot;: {
        &quot;chance&quot;: 10,
        &quot;boosts&quot;: {
          &quot;spd&quot;: -1
        }
      }
    },
    {
      &quot;secondary&quot;: {
        &quot;chance&quot;: 30,
        &quot;volatileStatus&quot;: &quot;flinch&quot;
      }
    },
    {
      &quot;secondary&quot;: {
        &quot;chance&quot;: 30
      }
    },
    {
      &quot;secondary&quot;: {
        &quot;chance&quot;: 10,
        &quot;self&quot;: {
          &quot;boosts&quot;: {
            &quot;atk&quot;: 1,
            &quot;def&quot;: 1,
            &quot;spa&quot;: 1,
            &quot;spd&quot;: 1,
            &quot;spe&quot;: 1
          }
        }
      }
    },
    {
      &quot;secondary&quot;: {
        &quot;chance&quot;: 10,
        &quot;status&quot;: &quot;brn&quot;
      }
    },
    {
      &quot;secondary&quot;: {
        &quot;chance&quot;: 50,
        &quot;self&quot;: {
          &quot;boosts&quot;: {
            &quot;def&quot;: 2
          }
        }
      }
    },
    {
      &quot;secondary&quot;: {
        &quot;chance&quot;: 100,
        &quot;self&quot;: {}
      }
    },
    {
      &quot;secondary&quot;: {
        &quot;chance&quot;: 50,
        &quot;boosts&quot;: {
          &quot;accuracy&quot;: -1
        }
      }
    }
  ]
  </code></pre>
  <p>For your convenience, you can choose to attach this snippet to the end of the js file and run it using <code>node move.js</code>. Two valid json files will be saved to your disk. One is a list of json objects while the other is an object with string as key.</p>
  <pre><code>
  var fs = require('fs');
  fs.writeFile(&quot;moves_object.json&quot;, JSON.stringify(BattleMovedex), function(err) {}); // 1. save a json object with string key
  
  var jsonList = []
  for (var key of Object.keys(BattleMovedex)) {
      jsonList.push(BattleMovedex[key]);
  }
  fs.writeFile(&quot;moves.json&quot;, JSON.stringify(jsonList), function(err) { // 2. save as a list of json object
      if (err) {
          console.log(err);
      }
  });
  
  </code></pre>
  <p><strong>FYI</strong>:
  If you are familiar with c++, you might find it easier to understand the same problem in this post:</p>
  <p><a href="https://stackoverflow.com/questions/60643750/how-to-parse-json-file-with-stdoptional-stdvariant-type-in-c">How to parse json file with std::optional&lt; std::variant &gt; type in C++?</a></p>