object.go 810 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package json
  2. import (
  3. "bytes"
  4. )
  5. // Object represents the encoding of a JSON Object type
  6. type Object struct {
  7. w *bytes.Buffer
  8. writeComma bool
  9. scratch *[]byte
  10. }
  11. func newObject(w *bytes.Buffer, scratch *[]byte) *Object {
  12. w.WriteRune(leftBrace)
  13. return &Object{w: w, scratch: scratch}
  14. }
  15. func (o *Object) writeKey(key string) {
  16. escapeStringBytes(o.w, []byte(key))
  17. o.w.WriteRune(colon)
  18. }
  19. // Key adds the given named key to the JSON object.
  20. // Returns a Value encoder that should be used to encode
  21. // a JSON value type.
  22. func (o *Object) Key(name string) Value {
  23. if o.writeComma {
  24. o.w.WriteRune(comma)
  25. } else {
  26. o.writeComma = true
  27. }
  28. o.writeKey(name)
  29. return newValue(o.w, o.scratch)
  30. }
  31. // Close encodes the end of the JSON Object
  32. func (o *Object) Close() {
  33. o.w.WriteRune(rightBrace)
  34. }