all repos

json2go @ af830300d091d01c29c65a9cd666325590dc1eae

convert json to go type annotations

json2go/json2go.go(view raw)

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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package json2go

import (
	"encoding/json"
	"errors"
	"fmt"
	"strings"
)

var ErrInvalidJSON = errors.New("invalid json")

type (
	types       struct{ name, def string }
	Transformer struct {
		structName string
		types      []types
	}
)

func NewTransformer() *Transformer {
	return &Transformer{}
}

// Transform ...
// todo: take io.Reader as input?
// todo: output as io.Writer?
// todo: validate provided structName
func (t *Transformer) Transform(structName, jsonStr string) (string, error) {
	t.structName = structName
	t.types = make([]types, 1)

	var input any
	if err := json.Unmarshal([]byte(jsonStr), &input); err != nil {
		return "", errors.Join(ErrInvalidJSON, err)
	}

	var result strings.Builder

	// the "parent" type
	type_ := t.generateTypeAnnotation(structName, input)
	result.WriteString(type_)

	// nested types
	for _, t := range t.types {
		if t.name != structName {
			result.WriteString(t.def)
			result.WriteString("\n")
		}
	}

	return result.String(), nil
}

func (t *Transformer) generateTypeAnnotation(typeName string, input any) string {
	switch v := input.(type) {
	case map[string]any:
		return t.buildStruct(typeName, v)

	case []any:
		if len(v) == 0 {
			return fmt.Sprintf("type %s []any", t.structName)
		}

		type_ := t.getGoType(typeName+"Item", v[0])
		return fmt.Sprintf("type %s []%s", typeName, type_)

	case string:
		return fmt.Sprintf("type %s string", typeName)

	case float64:
		if float64(int(v)) == v {
			return fmt.Sprintf("type %s int", typeName)
		}
		return fmt.Sprintf("type %s float64", typeName)

	case bool:
		return fmt.Sprintf("type %s bool", typeName)

	case nil:
		return fmt.Sprintf("type %s any", typeName)

	default:
		return fmt.Sprintf("type %s any", typeName)

	}
}

// todo: input shouldn't be map, to preserve it's order
func (t *Transformer) buildStruct(typeName string, input map[string]any) string {
	var fields strings.Builder
	for key, value := range input {
		fieldName := t.toGoFieldName(key)
		if fieldName == "" {
			fieldName = "Field"
		}

		fieldType := t.getGoType(fieldName, value)

		// todo: toggle json tags generation
		jsonTag := fmt.Sprintf("`json:\"%s\"`", key)

		// todo: figure out the indentation, since it might have nested struct
		fields.WriteString(fmt.Sprintf(
			"%s %s %s\n",
			fieldName,
			fieldType,
			jsonTag,
		))
	}

	structDef := fmt.Sprintf("type %s struct {\n%s}", typeName, fields.String())
	t.types = append(t.types, types{
		name: typeName,
		def:  structDef,
	})

	return structDef
}

func (t *Transformer) getGoType(fieldName string, value any) string {
	switch v := value.(type) {
	case map[string]any:
		typeName := t.toGoTypeName(fieldName)
		if !t.isTypeRecorded(typeName) {
			t.generateTypeAnnotation(typeName, v)
		}
		return typeName

	case []any:
		if len(v) == 0 {
			return "[]any"
		}

		type_ := t.getGoType(fieldName+"Item", v[0]) // TODO
		return "[]" + type_

	case float64:
		if float64(int(v)) == v {
			return "int"
		}
		return "float64"

	case string:
		return "string"

	case bool:
		return "bool"

	case nil:
		return "any"

	default:
		return "any"
	}
}

func (t *Transformer) toGoTypeName(fieldName string) string {
	goName := t.toGoFieldName(fieldName)
	if len(goName) > 0 {
		return strings.ToUpper(goName[:1]) + goName[1:]
	}
	return "Type"
}

func (t *Transformer) toGoFieldName(jsonField string) string {
	parts := strings.Split(jsonField, "_")

	var result strings.Builder
	for _, part := range parts {
		if part != "" {
			if len(part) > 0 {
				result.WriteString(strings.ToUpper(part[:1]) + part[1:])
			}
		}
	}

	return result.String()
}

func (t *Transformer) isTypeRecorded(name string) bool {
	for _, t := range t.types {
		if t.name == name {
			return true
		}
	}
	return false
}