title: Python JSON encoder convert NaNs to null instead
body: <p>I'm writing code to receive an arbitrary object (possibly nested) capable of being converted to JSON.</p>
  <p>The default behavior for Python's builtin JSON encoder is to convert NaNs to <code>NaN</code>, e.g. <code>json.dumps(np.NaN)</code> results in <code>NaN</code>.  How can I change this <code>NaN</code> value to <code>null</code>?</p>
  <p>I tried to <a href="https://docs.python.org/3/library/json.html#json.JSONEncoder" rel="noreferrer">subclass <code>JSONEncoder</code> and override the <code>default()</code> method</a> as follows:</p>
  <pre><code>from json import JSONEncoder, dumps
  import numpy as np
      
  class NanConverter(JSONEncoder):
      def default(self, obj):
          try:
              _ = iter(obj)
          except TypeError:
              if isinstance(obj, float) and np.isnan(obj):
                  return &quot;null&quot;
          return JSONEncoder.default(self, obj)
  
  &gt;&gt;&gt; d = {'a': 1, 'b': 2, 'c': 3, 'e': np.nan, 'f': [1, np.nan, 3]}
  &gt;&gt;&gt; dumps(d, cls=NanConverter)
  '{&quot;a&quot;: 1, &quot;c&quot;: 3, &quot;b&quot;: 2, &quot;e&quot;: NaN, &quot;f&quot;: [1, NaN, 3]}'
  </code></pre>
  <p>EXPECTED RESULT: <code>'{&quot;a&quot;: 1, &quot;c&quot;: 3, &quot;b&quot;: 2, &quot;e&quot;: null, &quot;f&quot;: [1, null, 3]}'</code></p>