• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

LICENSEH A D16-Oct-20181 KiB

README.mdH A D16-Oct-20185.6 KiB

gabs.goH A D16-Oct-201818 KiB

gabs_test.goH A D16-Oct-201829.7 KiB

README.md

1![Gabs](gabs_logo.png "Gabs")
2
3Gabs is a small utility for dealing with dynamic or unknown JSON structures in
4golang. It's pretty much just a helpful wrapper around the golang
5`json.Marshal/json.Unmarshal` behaviour and `map[string]interface{}` objects.
6It does nothing spectacular except for being fabulous.
7
8https://godoc.org/github.com/Jeffail/gabs
9
10## How to install:
11
12``` bash
13go get github.com/Jeffail/gabs
14```
15
16## How to use
17
18### Parsing and searching JSON
19
20``` go
21...
22
23import "github.com/Jeffail/gabs"
24
25jsonParsed, err := gabs.ParseJSON([]byte(`{
26	"outter":{
27		"inner":{
28			"value1":10,
29			"value2":22
30		},
31		"alsoInner":{
32			"value1":20
33		}
34	}
35}`))
36
37var value float64
38var ok bool
39
40value, ok = jsonParsed.Path("outter.inner.value1").Data().(float64)
41// value == 10.0, ok == true
42
43value, ok = jsonParsed.Search("outter", "inner", "value1").Data().(float64)
44// value == 10.0, ok == true
45
46value, ok = jsonParsed.Path("does.not.exist").Data().(float64)
47// value == 0.0, ok == false
48
49exists := jsonParsed.Exists("outter", "inner", "value1")
50// exists == true
51
52exists := jsonParsed.Exists("does", "not", "exist")
53// exists == false
54
55exists := jsonParsed.ExistsP("does.not.exist")
56// exists == false
57
58...
59```
60
61### Iterating objects
62
63``` go
64...
65
66jsonParsed, _ := gabs.ParseJSON([]byte(`{"object":{ "first": 1, "second": 2, "third": 3 }}`))
67
68// S is shorthand for Search
69children, _ := jsonParsed.S("object").ChildrenMap()
70for key, child := range children {
71	fmt.Printf("key: %v, value: %v\n", key, child.Data().(string))
72}
73
74...
75```
76
77### Iterating arrays
78
79``` go
80...
81
82jsonParsed, _ := gabs.ParseJSON([]byte(`{"array":[ "first", "second", "third" ]}`))
83
84// S is shorthand for Search
85children, _ := jsonParsed.S("array").Children()
86for _, child := range children {
87	fmt.Println(child.Data().(string))
88}
89
90...
91```
92
93Will print:
94
95```
96first
97second
98third
99```
100
101Children() will return all children of an array in order. This also works on
102objects, however, the children will be returned in a random order.
103
104### Searching through arrays
105
106If your JSON structure contains arrays you can still search the fields of the
107objects within the array, this returns a JSON array containing the results for
108each element.
109
110``` go
111...
112
113jsonParsed, _ := gabs.ParseJSON([]byte(`{"array":[ {"value":1}, {"value":2}, {"value":3} ]}`))
114fmt.Println(jsonParsed.Path("array.value").String())
115
116...
117```
118
119Will print:
120
121```
122[1,2,3]
123```
124
125### Generating JSON
126
127``` go
128...
129
130jsonObj := gabs.New()
131// or gabs.Consume(jsonObject) to work on an existing map[string]interface{}
132
133jsonObj.Set(10, "outter", "inner", "value")
134jsonObj.SetP(20, "outter.inner.value2")
135jsonObj.Set(30, "outter", "inner2", "value3")
136
137fmt.Println(jsonObj.String())
138
139...
140```
141
142Will print:
143
144```
145{"outter":{"inner":{"value":10,"value2":20},"inner2":{"value3":30}}}
146```
147
148To pretty-print:
149
150``` go
151...
152
153fmt.Println(jsonObj.StringIndent("", "  "))
154
155...
156```
157
158Will print:
159
160```
161{
162  "outter": {
163    "inner": {
164      "value": 10,
165      "value2": 20
166    },
167    "inner2": {
168      "value3": 30
169    }
170  }
171}
172```
173
174### Generating Arrays
175
176``` go
177...
178
179jsonObj := gabs.New()
180
181jsonObj.Array("foo", "array")
182// Or .ArrayP("foo.array")
183
184jsonObj.ArrayAppend(10, "foo", "array")
185jsonObj.ArrayAppend(20, "foo", "array")
186jsonObj.ArrayAppend(30, "foo", "array")
187
188fmt.Println(jsonObj.String())
189
190...
191```
192
193Will print:
194
195```
196{"foo":{"array":[10,20,30]}}
197```
198
199Working with arrays by index:
200
201``` go
202...
203
204jsonObj := gabs.New()
205
206// Create an array with the length of 3
207jsonObj.ArrayOfSize(3, "foo")
208
209jsonObj.S("foo").SetIndex("test1", 0)
210jsonObj.S("foo").SetIndex("test2", 1)
211
212// Create an embedded array with the length of 3
213jsonObj.S("foo").ArrayOfSizeI(3, 2)
214
215jsonObj.S("foo").Index(2).SetIndex(1, 0)
216jsonObj.S("foo").Index(2).SetIndex(2, 1)
217jsonObj.S("foo").Index(2).SetIndex(3, 2)
218
219fmt.Println(jsonObj.String())
220
221...
222```
223
224Will print:
225
226```
227{"foo":["test1","test2",[1,2,3]]}
228```
229
230### Converting back to JSON
231
232This is the easiest part:
233
234``` go
235...
236
237jsonParsedObj, _ := gabs.ParseJSON([]byte(`{
238	"outter":{
239		"values":{
240			"first":10,
241			"second":11
242		}
243	},
244	"outter2":"hello world"
245}`))
246
247jsonOutput := jsonParsedObj.String()
248// Becomes `{"outter":{"values":{"first":10,"second":11}},"outter2":"hello world"}`
249
250...
251```
252
253And to serialize a specific segment is as simple as:
254
255``` go
256...
257
258jsonParsedObj := gabs.ParseJSON([]byte(`{
259	"outter":{
260		"values":{
261			"first":10,
262			"second":11
263		}
264	},
265	"outter2":"hello world"
266}`))
267
268jsonOutput := jsonParsedObj.Search("outter").String()
269// Becomes `{"values":{"first":10,"second":11}}`
270
271...
272```
273
274### Merge two containers
275
276You can merge a JSON structure into an existing one, where collisions will be
277converted into a JSON array.
278
279``` go
280jsonParsed1, _ := ParseJSON([]byte(`{"outter": {"value1": "one"}}`))
281jsonParsed2, _ := ParseJSON([]byte(`{"outter": {"inner": {"value3": "three"}}, "outter2": {"value2": "two"}}`))
282
283jsonParsed1.Merge(jsonParsed2)
284// Becomes `{"outter":{"inner":{"value3":"three"},"value1":"one"},"outter2":{"value2":"two"}}`
285```
286
287Arrays are merged:
288
289``` go
290jsonParsed1, _ := ParseJSON([]byte(`{"array": ["one"]}`))
291jsonParsed2, _ := ParseJSON([]byte(`{"array": ["two"]}`))
292
293jsonParsed1.Merge(jsonParsed2)
294// Becomes `{"array":["one", "two"]}`
295```
296
297### Parsing Numbers
298
299Gabs uses the `json` package under the bonnet, which by default will parse all
300number values into `float64`. If you need to parse `Int` values then you should
301use a `json.Decoder` (https://golang.org/pkg/encoding/json/#Decoder):
302
303``` go
304sample := []byte(`{"test":{"int":10, "float":6.66}}`)
305dec := json.NewDecoder(bytes.NewReader(sample))
306dec.UseNumber()
307
308val, err := gabs.ParseJSONDecoder(dec)
309if err != nil {
310    t.Errorf("Failed to parse: %v", err)
311    return
312}
313
314intValue, err := val.Path("test.int").Data().(json.Number).Int64()
315```
316