write.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jsonutils
  15. import (
  16. "fmt"
  17. "strings"
  18. "yunion.io/x/pkg/sortedmap"
  19. )
  20. type writeSource interface {
  21. buildString(sb *strings.Builder)
  22. }
  23. func (this *JSONString) buildString(sb *strings.Builder) {
  24. sb.WriteString(this.String())
  25. }
  26. func (this *JSONValue) buildString(sb *strings.Builder) {
  27. sb.WriteString(this.String())
  28. }
  29. func (this *JSONInt) buildString(sb *strings.Builder) {
  30. sb.WriteString(this.String())
  31. }
  32. func (this *JSONFloat) buildString(sb *strings.Builder) {
  33. sb.WriteString(this.String())
  34. }
  35. func (this *JSONBool) buildString(sb *strings.Builder) {
  36. sb.WriteString(this.String())
  37. }
  38. func (this *JSONDict) buildString(sb *strings.Builder) {
  39. sb.WriteByte('{')
  40. var idx = 0
  41. if this.nodeId > 0 {
  42. sb.WriteString(quoteString(jsonPointerKey))
  43. sb.WriteByte(':')
  44. sb.WriteString(fmt.Sprintf("%d", this.nodeId))
  45. idx++
  46. }
  47. for iter := sortedmap.NewIterator(this.data); iter.HasMore(); iter.Next() {
  48. k, vinf := iter.Get()
  49. v := vinf.(JSONObject)
  50. if idx > 0 {
  51. sb.WriteByte(',')
  52. }
  53. sb.WriteString(quoteString(k))
  54. sb.WriteByte(':')
  55. v.buildString(sb)
  56. idx++
  57. }
  58. sb.WriteByte('}')
  59. }
  60. func (this *JSONArray) buildString(sb *strings.Builder) {
  61. sb.WriteByte('[')
  62. for idx, v := range this.data {
  63. if idx > 0 {
  64. sb.WriteByte(',')
  65. }
  66. v.buildString(sb)
  67. }
  68. sb.WriteByte(']')
  69. }