-
-
Notifications
You must be signed in to change notification settings - Fork 59
/
json.go
79 lines (70 loc) · 2.21 KB
/
json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package faker
import (
"encoding/json"
"strconv"
)
// Json is a faker struct for json files
type Json struct {
Faker *Faker
}
var (
attributesTypes = []string{"string", "number", "object", "array", "boolean", "null"}
attributesTypesWithoutArrayAndObject = []string{"string", "number", "boolean", "null"}
)
func (j *Json) randomAttributeValueFromListAsString(validAttributesTypes []string) string {
attributeType := j.Faker.RandomStringElement(validAttributesTypes)
switch attributeType {
case "string":
return "\"" + j.Faker.Lorem().Word() + "\""
case "number":
number := strconv.Itoa(j.Faker.RandomNumber(j.Faker.RandomDigit()))
return number
case "object":
// Avoid having multiple nested objects by not using object and array as valid attribute types
return j.randomJsonObjectAsString(attributesTypesWithoutArrayAndObject)
case "array":
objects := ""
for i := 0; i < j.Faker.IntBetween(1, 10); i++ {
if objects != "" {
objects += ", "
}
// Avoid having multiple nested objects by not using object and array as valid attribute types
objects += j.randomJsonObjectAsString(attributesTypesWithoutArrayAndObject)
}
return "[" + objects + "]"
case "boolean":
return j.Faker.RandomStringElement([]string{"true", "false"})
case "null":
return "null"
}
panic("Invalid attribute type: " + attributeType)
}
func (j *Json) randomJsonObjectAsString(validAttributesTypes []string) string {
numberAttributes := j.Faker.IntBetween(1, 10)
attributes := make([]string, numberAttributes)
for i := 0; i < numberAttributes; i++ {
attributeName := j.Faker.Lorem().Word()
attributeValue := j.randomAttributeValueFromListAsString(validAttributesTypes)
attributes[i] = "\"" + attributeName + "\": " + attributeValue
}
result := "{"
for i := 0; i < len(attributes); i++ {
if i > 0 {
result += ", "
}
result += attributes[i]
}
result += "}"
return result
}
// String generates a random json string
func (j *Json) String() string {
return j.randomJsonObjectAsString(attributesTypes)
}
// Object generates a random json object
func (j *Json) Object() map[string]interface{} {
result := j.String()
var data map[string]interface{}
json.Unmarshal([]byte(result), &data)
return data
}