module JsonWriting { 
 
  import { ../Json; } 
   
  // JsonWriter 
 
  pub mut struct JsonWriter { 
    parts : mut string[]; 
  } 
 
  pub output.get(this : JsonWriter) : string => { 
    return this.parts.join(); 
  } 
 
  pub writeValue(this : JsonWriter, value : JsonValue) { 
    match (value) { 
      @val : JsonArray => this.writeArray(val); 
      @val : JsonObject => this.writeObject(val); 
      @val : double => this.writeNumber(val); 
      @val : bool => this.writeBool(val); 
      @val : none => this.writeNull(); 
      @val : string => this.writeString(val); 
    } 
  } 
 
  writeChar(this : JsonWriter, ch : char) { 
    this.parts.append(ch::string); 
  } 
 
  writeText(this : JsonWriter, text : string) { 
    this.parts.append(text); 
  } 
 
  writeString(this : JsonWriter, text : string) { 
    this.writeChar('"'); 
    // TODO: escape characters 
    this.writeText(text); 
    this.writeChar('"'); 
  } 
 
  writeBool(this : JsonWriter, val : bool) { 
    match (val) { 
      true => this.writeText("true"); 
      false => this.writeText("false"); 
    } 
  } 
 
  writeNumber(this : JsonWriter, val : double) { 
    this.writeText(val::string); 
  } 
 
  writeNull(this : JsonWriter) { 
    this.writeText("null"); 
  } 
 
  writeObject(this : JsonWriter, object : JsonObject) { 
    this.writeChar('{'); 
    for ((key, val), index in object) { 
      if (index > 0) { 
        this.writeChar(','); 
      } 
      this.writeString(key); 
      this.writeChar(':'); 
      this.writeValue(val); 
    } 
    this.writeChar('}'); 
  } 
 
  writeArray(this : JsonWriter, array : JsonArray) { 
    this.writeChar('['); 
    for (val, index in array) { 
      if (index > 0) { 
        this.writeChar(','); 
      } 
      this.writeValue(val); 
    } 
    this.writeChar(']'); 
  } 
 
}