You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

133 lines
2.0 KiB

5 years ago
5 years ago
  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. }