title: Python - how to remove the final comma(,) in json string
body: <p>Hi I have just started experimenting with python and tornado along with mongodb(I am a newbie). I have written a simple get function to get all the values from my mongodb and return it in JSON format. The problem is when I try to write the output as a JSON string I get a trailing comma(,) after the last record from the collection.</p>
  
  <pre><code>class TypeList(APIHandler):
  @gen.coroutine
  def get(self):
      cursor = db.vtype.find()
      self.write("{"'"success"'": 1, "'"data"'":[")
      while (yield cursor.fetch_next):
          document = cursor.next_object()
          self.write(format(JSONEncoder().encode(document)))
          self.write(",")
      self.write("]}")
  
  class JSONEncoder(json.JSONEncoder):
  def default(self, o):
      if isinstance(o,ObjectId):
          return str(o)
      return json.JSONEncoder.default(self, o)
  </code></pre>
  
  <p>And my output is like</p>
  
  <pre><code>{"success": 1, "data":[{"_id": "55a5e988545779f35d3ecdf4", "name": "fgkd", "city": "fghj"},{"_id": 12345.0, "name": "adfs", "city": "asd"},]}
  </code></pre>
  
  <p>Can anyone tell me how can I get rid of that trailing comma(,) after my last record, because of that comma I am getting an error malformed JSON string</p>
  
  <p>I have tried using json dumps</p>
  
  <pre><code>@gen.coroutine
  def get(self):
      cursor = db.vtype.find({"brand": "Tata"})
      while (yield cursor.fetch_next):
          document = cursor.next_object()
          self.write(json.dumps(document,default=json_util.default))
  </code></pre>
  
  <p>got the output as </p>
  
  <p><code>{"Reg": "11ts", "_id": {"$oid": "55a5e988545779f35d3ecdf4"}, "Name": "Alex"}{"Reg": "12ts", "_id": {"$oid": "55a5eac6545779f35d3ecdf5"}, "Name": "asdf"}</code></p>
  
  <p>When using <code>dumps[{ "data": document }]</code></p>
  
  <p>I am getting the output as</p>
  
  <pre><code>[{"data": {"Name": "asdf", "Reg": "asdfs", "_id": {"$oid": "55a5e988545779f35d3ecdf4"}}}]
  
  [{"data": {"Name": "qwer", "Reg": "asdff", "_id": {"$oid": "55a5eac6545779f35d3ecdf5"}}}]
  </code></pre>
  
  <p>but I want the output like this</p>
  
  <pre><code>{"data": [{"Name": "asdf", "Reg": "asdfs", "_id": {"$oid": "55a5e988545779f35d3ecdf4"}},{"Name": "qwer", "Reg": "asdff", "_id": {"$oid": "55a5eac6545779f35d3ecdf5"}}]}
  </code></pre>
  
  <p>If I am doing something wrong please tell me I dont know how to do it.</p>