query_json_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. package json
  2. import (
  3. "testing"
  4. "github.com/tidwall/gjson"
  5. )
  6. func TestGjson(t *testing.T) {
  7. data := `
  8. {
  9. "quiz": {
  10. "sport": {
  11. "q1": {
  12. "question": "Which one is correct team name in NBA?",
  13. "options": [
  14. "New York Bulls",
  15. "Los Angeles Kings",
  16. "Golden State Warriros",
  17. "Huston Rocket"
  18. ],
  19. "answer": "Huston Rocket"
  20. }
  21. },
  22. "maths": {
  23. "q1": {
  24. "question": "5 + 7 = ?",
  25. "options": [
  26. "10",
  27. "11",
  28. "12",
  29. "13"
  30. ],
  31. "answer": "12"
  32. },
  33. "q2": {
  34. "question": "12 - 8 = ?",
  35. "options": [
  36. "1",
  37. "2",
  38. "3",
  39. "4"
  40. ],
  41. "answer": "4"
  42. }
  43. }
  44. }
  45. }
  46. {
  47. "fruit": "Apple",
  48. "size": "Large",
  49. "quiz": "Red"
  50. }
  51. `
  52. projections := []string{"quiz", "fruit"}
  53. gjson.ForEachLine(data, func(line gjson.Result) bool {
  54. println(line.Raw)
  55. println("+++++++++++")
  56. results := gjson.GetMany(line.Raw, projections...)
  57. for _, result := range results {
  58. println(result.Index, result.Type, result.String())
  59. }
  60. println("-----------")
  61. return true
  62. })
  63. }
  64. func TestJsonQueryRow(t *testing.T) {
  65. data := `
  66. {
  67. "fruit": "Bl\"ue",
  68. "size": 6,
  69. "quiz": "green"
  70. }
  71. `
  72. selections := []string{"fruit", "size"}
  73. isFiltered, values := QueryJson(data, selections, Query{
  74. Field: "quiz",
  75. Op: "=",
  76. Value: "green",
  77. })
  78. if !isFiltered {
  79. t.Errorf("should have been filtered")
  80. }
  81. if values == nil {
  82. t.Errorf("values should have been returned")
  83. }
  84. buf := ToJson(nil, selections, values)
  85. println(string(buf))
  86. }
  87. func TestJsonQueryNumber(t *testing.T) {
  88. data := `
  89. {
  90. "fruit": "Bl\"ue",
  91. "size": 6,
  92. "quiz": "green"
  93. }
  94. `
  95. selections := []string{"fruit", "quiz"}
  96. isFiltered, values := QueryJson(data, selections, Query{
  97. Field: "size",
  98. Op: ">=",
  99. Value: "6",
  100. })
  101. if !isFiltered {
  102. t.Errorf("should have been filtered")
  103. }
  104. if values == nil {
  105. t.Errorf("values should have been returned")
  106. }
  107. buf := ToJson(nil, selections, values)
  108. println(string(buf))
  109. }