Jason intends to be an idiomatic JSON library for Go. Inspired by other libraries and improved to work well for common use cases.
go get github.com/antonholmquist/jason`
import (
"github.com/antonholmquist/jason"
)
Create a instance from a string. Returns an error if the string couldn't be parsed.
root, err := jason.NewFromString(s)
Create a instance from a net/http response. Returns an error if the string couldn't be parsed.
root, err := jason.NewFromReader(res.Body)
Reading values is easy. If the key is invalid, it will return the default value.
root.Get("name").String()
root.Get("age").Number()
root.Get("verified").Bool()
root.Get("education").Object()
root.Get("friends").Array()
Reading nested values is easy. If the path is invalid, it will return the default value, for instance the empty string.
root.Get("person", "name").String()
root.Get("person", "age").Number()
root.Get("person", "verified").Bool()
root.Get("person", "education").Object()
root.Get("person", "friends").Array()
To check if a value exist, use Has()
or Exists()
. The two examples below are identical and have different use cases.
root.Has("person", "name")
root.Get("person", "name").Exists()
To check if a value at the keypath really is what you think it is, use the Is()-methods
.
root.Get("name").IsString()
root.Get("age").IsNumber()
root.Get(""verified").IsBool()
root.Get("education").IsObject()
root.Get("friends").IsArray()
Looping through an array is easy and will never return an exeption. Array()
returns an empty array if the value at that keypath is null or something else than an array.
for _, friend := person.Get("friends").Array() {
name := friend.Get("name").String()
age := friend.Get("age").Number()
}
https://godoc.org/github.com/antonholmquist/jason
package main
import (
"github.com/antonholmquist/jason"
"log"
)
func main() {
exampleJSON := `{
"name": "Walter White",
"age": 51,
"children": [
"junior",
"holly"
],
"other": {
"occupation": "chemist",
"years": 23
}
}`
j, _ := jason.NewFromString(exampleJSON)
log.Println("name:", j.Get("name").String())
log.Println("age:", j.Get("age").Number())
log.Println("occupation:", j.Get("other", "occupation").String())
log.Println("years:", j.Get("other", "years").Number())
for i, child := range j.Get("children").Array() {
log.Printf("child %d: %s", i, child.String())
}
}
To run the project tests:
go test