docs: def dump(doc, output_stream=None):
      """
      Dump a :class:`.Doc` object into a JSON-encoded text string.
  
      The output will be sent to :data:`sys.stdout` unless an alternative
      text stream is given.
  
      To dump to :data:`sys.stdout` just do:
  
          >>> import panflute as pf
          >>> doc = pf.Doc(Para(Str('a')))  # Create sample document
          >>> pf.dump(doc)
  
      To dump to file:
  
          >>> with open('some-document.json', 'w'. encoding='utf-8') as f:
          >>>     pf.dump(doc, f)
  
      To dump to a  string:
  
          >>> import io
          >>> with io.StringIO() as f:
          >>>     pf.dump(doc, f)
          >>>     contents = f.getvalue()
  
      :param doc: document, usually created with :func:`.load`
      :type doc: :class:`.Doc`
      :param output_stream: text stream used as output
          (default is :data:`sys.stdout`)
      """
  
      assert type(doc) == Doc, "panflute.dump needs input of type panflute.Doc"
      if output_stream is None:
          sys.stdout = codecs.getwriter("utf-8")(sys.stdout) if py2 else codecs.getwriter("utf-8")(sys.stdout.detach())
          output_stream = sys.stdout
  
      # Switch to legacy JSON output; eg: {'t': 'Space', 'c': []}
      if doc.api_version is None:
  
          # Switch .to_json() to legacy
          Citation.backup = Citation.to_json
          Citation.to_json = Citation.to_json_legacy
  
          # Switch ._slots_to_json() to legacy
          for E in [Table, OrderedList, Quoted, Math]:
              E.backup = E._slots_to_json
              E._slots_to_json = E._slots_to_json_legacy
  
          # Switch .to_json() to method of base class
          for E in EMPTY_ELEMENTS:
              E.backup = E.to_json
              E.to_json = Element.to_json
  
      json_serializer = lambda elem: elem.to_json()
  
      output_stream.write(json.dumps(
          obj=doc,
          default=json_serializer,  # Serializer
          check_circular=False,
          separators=(',', ':'),  # Compact separators, like Pandoc
          ensure_ascii=False  # For Pandoc compat
      ))
  
      # Undo legacy changes
      if doc.api_version is None:
          Citation.to_json = Citation.backup
          for E in [Table, OrderedList, Quoted, Math]:
              E._slots_to_json = E.backup
          for E in EMPTY_ELEMENTS:
              E.to_json = E.backup