Last active
December 9, 2016 07:31
-
-
Save diabloneo/88533e60fbe1233651ae to your computer and use it in GitHub Desktop.
Set array element of a JSON using go-simplejson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
running result: