Skip to content

Instantly share code, notes, and snippets.

@diabloneo
Last active December 9, 2016 07:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diabloneo/88533e60fbe1233651ae to your computer and use it in GitHub Desktop.
Save diabloneo/88533e60fbe1233651ae to your computer and use it in GitHub Desktop.
Set array element of a JSON using go-simplejson
package main
import (
"fmt"
"github.com/bitly/go-simplejson"
)
func testJsonArray1(pgStatsJson []*simplejson.Json) {
fmt.Println("testJsonArray1")
j := simplejson.New()
pgStats := make([]interface{}, 0, 10)
if pgStatsJson != nil {
for _, pgStat := range pgStatsJson {
pgStats = append(pgStats, pgStat.MustMap())
}
}
j.Set("pg_stats", pgStats)
if _, err := j.GetPath("pg_stats").Array(); err != nil {
fmt.Println(err)
}
fmt.Println(j)
}
func testJsonArray2(pgStatsJson []*simplejson.Json) {
fmt.Println("testJsonArray2")
j := simplejson.New()
pgStats := make([]map[string]interface{}, 0, 10) // different type
if pgStatsJson != nil {
for _, pgStat := range pgStatsJson {
pgStats = append(pgStats, pgStat.MustMap())
}
}
j.Set("pg_stats", pgStats)
if _, err := j.GetPath("pg_stats").Array(); err != nil {
fmt.Println(err)
}
fmt.Println(j)
}
func main() {
pgStat1, _ := simplejson.NewJson([]byte(`{"num_bytes": 1111}`))
pgStat2, _ := simplejson.NewJson([]byte(`{"num_bytes": 2222}`))
testJsonArray1([]*simplejson.Json{pgStat1, pgStat2})
testJsonArray1(nil)
fmt.Println()
testJsonArray2([]*simplejson.Json{pgStat1, pgStat2})
testJsonArray2(nil)
}
@diabloneo
Copy link
Author

running result:

testJsonArray1
&{map[pg_stats:[map[num_bytes:1111] map[num_bytes:2222]]]}
testJsonArray1
&{map[pg_stats:[]]}

testJsonArray2
type assertion to []interface{} failed
&{map[pg_stats:[map[num_bytes:1111] map[num_bytes:2222]]]}
testJsonArray2
type assertion to []interface{} failed
&{map[pg_stats:[]]}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment