dict.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. "yunion.io/x/pkg/sortedmap"
  17. )
  18. func (dict *JSONDict) Update(json JSONObject) {
  19. dict2, ok := json.(*JSONDict)
  20. if !ok {
  21. return
  22. }
  23. dict.data = sortedmap.Merge(dict.data, dict2.data)
  24. }
  25. func (dict *JSONDict) UpdateDefault(json JSONObject) {
  26. dict2, ok := json.(*JSONDict)
  27. if !ok {
  28. return
  29. }
  30. dict.data = sortedmap.Merge(dict2.data, dict.data)
  31. }
  32. func Diff(a, b *JSONDict) (aNoB, aDiffB, aAndB, bNoA *JSONDict) {
  33. aNoB = NewDict()
  34. aDiffB = NewDict()
  35. aAndB = NewDict()
  36. bNoA = NewDict()
  37. var aData, bData sortedmap.SSortedMap
  38. aNoB.data, aData, bData, bNoA.data = sortedmap.Split(a.data, b.data)
  39. for _, k := range aData.Keys() {
  40. aVal, _ := aData.Get(k)
  41. bVal, _ := bData.Get(k)
  42. aJson := aVal.(JSONObject)
  43. bJson := bVal.(JSONObject)
  44. if !aJson.Equals(bJson) {
  45. aDiffB.Set(k, NewArray(aJson, bJson))
  46. } else {
  47. aAndB.Set(k, aJson)
  48. }
  49. }
  50. return
  51. }