本文整理汇总了Golang中github.com/antonholmquist/jason.NewObjectFromBytes函数的典型用法代码示例。如果您正苦于以下问题:Golang NewObjectFromBytes函数的具体用法?Golang NewObjectFromBytes怎么用?Golang NewObjectFromBytes使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewObjectFromBytes函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: GetWeather
func GetWeather(city string, state string) {
json_link := fmt.Sprintf("%s/hourly/q/%s/%s.json", API_LINK, state, city)
resp, err := http.Get(json_link)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
v, err := jason.NewObjectFromBytes(body)
if err != nil {
log.Fatal(err)
}
hourlyForecast, err := v.GetObjectArray("hourly_forecast")
if err != nil {
log.Fatal(err)
}
for _, hourCast := range hourlyForecast {
stringhour, _ := hourCast.GetString("FCTTIME", "hour")
temp, _ := hourCast.GetString("temp", "english")
hour, _ := strconv.Atoi(stringhour)
if hour == time.Now().Hour() {
SendWeather(temp)
break
}
}
}
示例2: PollCmds
// Fetch commands
func (s *Client) PollCmds() {
bytes, err := s._get(fmt.Sprintf("client/%s/cmds", url.QueryEscape(s.Id)))
if err == nil {
obj, jerr := jason.NewObjectFromBytes(bytes)
if jerr == nil {
status, statusE := obj.GetString("status")
// Re-auth
if statusE != nil || status != "OK" {
log.Println(string(bytes))
log.Println("Re-authenticate with server")
s.AuthServer()
return
}
// List commands
cmds, _ := obj.GetObjectArray("cmds")
for _, cmd := range cmds {
id, _ := cmd.GetString("Id")
command, _ := cmd.GetString("Command")
signature, _ := cmd.GetString("Signature")
templateId, _ := cmd.GetString("TemplateId")
timeout, _ := cmd.GetInt64("Timeout")
cmd := newCmd(command, int(timeout))
cmd.ClientId = client.Id
cmd.TemplateId = templateId
cmd.Id = id
cmd.Signature = signature
cmd.Execute(s)
}
}
} else {
// In case of fast error back off a bit
time.Sleep(1 * time.Second)
}
}
示例3: extractBlogPosts
func extractBlogPosts() map[string]*BlogPost {
outcome := make(map[string]*BlogPost)
rawContent, readErr := ioutil.ReadFile(appConfiguration["saved_data_filename"].StringValue)
if readErr == nil {
json, _ := jason.NewObjectFromBytes(rawContent)
for k1, _ := range json.Map() {
hash := make(map[string]int)
author, _ := json.GetString(k1, "author")
headline, _ := json.GetString(k1, "headline")
date, _ := json.GetInt64(k1, "date")
contentHash, _ := json.GetObject(k1, "contentHash")
brief, _ := json.GetString(k1, "brief")
post := BlogPost{
k1,
author,
headline,
time.Unix(date, 0),
hash,
brief,
}
for k2, v2 := range contentHash.Map() {
n, _ := v2.Int64()
hash[k2] = int(n)
}
outcome[k1] = &post
}
}
return outcome
}
示例4: listContainers
func listContainers() {
response := instainerGet("/containers")
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
check(err)
v, err := jason.NewObjectFromBytes(contents)
data, err := v.GetObject("data")
permanents, err := data.GetObjectArray("permanents")
nonpermanents, err := data.GetObjectArray("nonPermanents")
banner.Print("instainer")
fmt.Println("")
fmt.Println("")
fmt.Println("Permanent Containers")
fmt.Println("")
fmt.Printf("%-32s %-52s %-32s %-24s\n", "CONTAINER ID", "NAME", "IMAGE NAME", "CREATED")
for _, container := range permanents {
containerId, err := container.GetString("id")
name, err := container.GetString("name")
imageName, err := container.GetString("imageName")
createdTime, err := container.GetString("createdTime")
check(err)
fmt.Printf("%-32s %-52s %-32s %-24s\n", containerId, name, imageName, createdTime)
}
fmt.Println("")
fmt.Println("")
fmt.Println("Non-Permanent Containers")
fmt.Println("")
fmt.Printf("%-32s %-52s %-32s %-24s\n", "CONTAINER ID", "NAME", "IMAGE NAME", "CREATED")
for _, container := range nonpermanents {
containerId, err := container.GetString("id")
name, err := container.GetString("name")
imageName, err := container.GetString("imageName")
createdTime, err := container.GetString("createdTime")
check(err)
fmt.Printf("%-32s %-52s %-32s %-24s\n", containerId, name, imageName, createdTime)
}
}
示例5: BenchmarkJasonSmall
func BenchmarkJasonSmall(b *testing.B) {
for i := 0; i < b.N; i++ {
json, _ := jason.NewObjectFromBytes(smallFixture)
json.GetString("uuid")
json.GetFloat64("tz")
json.GetString("ua")
json.GetFloat64("st")
nothing()
}
}
示例6: twitchDecode
func twitchDecode(stream []byte) string {
datajson, _ := jason.NewObjectFromBytes(stream)
game, err := datajson.GetString("stream", "game")
status, err := datajson.GetString("stream", "channel", "status")
url, err := datajson.GetString("stream", "channel", "url")
viewers, err := datajson.GetInt64("stream", "viewers")
streamname, err := datajson.GetString("stream", "channel", "name")
if err != nil {
return "Not Online or API server is down(probably not online)!"
}
return url + " " + streamname + " is online with " + strconv.Itoa(int(viewers)) + " viewers, Playing: " + game + "! " + status + "\n"
}
示例7: GetLanguageConfig
func GetLanguageConfig(lang string) LanguageConfig {
raw, _ := ioutil.ReadFile("./config.json")
decoded, _ := jason.NewObjectFromBytes([]byte(raw))
time, _ := decoded.GetInt64("Languages", lang, "Time")
memory, _ := decoded.GetInt64("Languages", lang, "Memory")
compile, _ := decoded.GetString("Languages", lang, "Compile")
run, _ := decoded.GetString("Languages", lang, "Run")
file, _ := decoded.GetString("FileName")
return LanguageConfig{
Time: time,
Memory: memory,
Compile: compile,
Run: run,
FilePlaceholder: file,
}
}
示例8: BenchmarkJasonMedium
func BenchmarkJasonMedium(b *testing.B) {
for i := 0; i < b.N; i++ {
json, _ := jason.NewObjectFromBytes(mediumFixture)
json.GetString("person.name.fullName")
json.GetFloat64("person.github.followers")
json.GetObject("company")
arr, _ := json.GetObjectArray("person.gravatar.avatars")
for _, el := range arr {
el.GetString("url")
}
nothing()
}
}
示例9: main
func main() {
// Use the same library and method we defined before
body := controller.GetHosts("https://sandboxapic.cisco.com")
// Use the JSON library, jason, to do the heavy lifting of creating go objects
v, _ := jason.NewObjectFromBytes(body)
// Since the result is an array of objects, we need to use GetObjectArray()
r, _ := v.GetObjectArray("response")
// Loop over the objects
for _, obj := range r {
// Use the jason library's GetString() method to get the right elements of the
// returned JSON.
//
// Example JSON
// {
// "connectedInterfaceId": "30bb14c1-8fb6-45c4-8f6d-5b845a7f448c",
// "connectedInterfaceName": "GigabitEthernet2/0/2",
// "connectedNetworkDeviceId": "7895a45f-47aa-42ee-9d06-c66d3b784594",
// "connectedNetworkDeviceIpAddress": "40.0.2.18",
// "hostIp": "40.0.5.12",
// "hostMac": "00:50:56:8A:27:A3",
// "hostType": "WIRED",
// "id": "8f41bef8-698c-4701-af14-471e910ed9ff",
// "lastUpdated": "September 29, 2014 1:54:13 PM PDT",
// "numUpdates": 1,
// "source": 200,
// "userStatus": "Active",
// "vlanId": "1"
// }
iFace, err := obj.GetString("connectedInterfaceId")
deviceType, err := obj.GetString("hostType")
log.Println("id: " + iFace + " type: " + deviceType)
if err != nil {
log.Println(err)
}
}
}
示例10: jsonDecode
func jsonDecode(data []byte) int {
updateidreturn := 1
datajson, _ := jason.NewObjectFromBytes(data)
result, _ := datajson.GetObjectArray("result")
for _, results := range result {
userid, _ := results.GetInt64("message", "from", "id")
chatid, _ := results.GetInt64("message", "chat", "id")
updateid, _ := results.GetInt64("update_id")
text, _ := results.GetString("message", "text")
username, _ := results.GetString("message", "from", "username")
firstname, _ := results.GetString("message", "from", "first_name")
lastname, _ := results.GetString("message", "from", "last_name")
fmt.Printf("[%d/%d]%s %s(%s): %s\n", userid, chatid, firstname, lastname, username, text)
go interpret(int(chatid), text)
updateidreturn = int(updateid)
}
return updateidreturn
}
示例11: FBLogin
func FBLogin(w http.ResponseWriter, r *http.Request) {
// grab the code fragment
w.Header().Set("Content-Type", "text/html; charset=utf-8")
code := r.FormValue("code")
ClientId := "137453133278122" // change this to yours
ClientSecret := "ee16109c966f12014bbcfccb4547813c"
RedirectURL := "http://localhost:8080/FBLogin"
accessToken := GetAccessToken(ClientId, code, ClientSecret, RedirectURL)
response, err := http.Get("https://graph.facebook.com/me?fields=id,email,first_name,last_name&access_token=" + accessToken.Token)
// handle err. You need to change this into something more robust
// such as redirect back to home page with error message
if err != nil {
w.Write([]byte(err.Error()))
}
str := readHttpBody(response)
//fmt.Println(str)
// dump out all the data
// w.Write([]byte(str))
// see https://www.socketloop.com/tutorials/golang-process-json-data-with-jason-package
user, _ := jason.NewObjectFromBytes([]byte(str))
id, _ := user.GetString("id")
email, _ := user.GetString("email")
fbFirstName, _ := user.GetString("first_name")
fbLastName, _ := user.GetString("last_name")
w.Write([]byte(fmt.Sprintf("Username %s %s ID is %s and email is %s<br>", fbFirstName, fbLastName, id, email)))
img := "https://graph.facebook.com/" + id + "/picture?width=180&height=180"
//w.Write([]byte("Photo is located at " + img + "<br>"))
// see https://www.socketloop.com/tutorials/golang-download-file-example on how to save FB file to disk
w.Write([]byte("<img src='" + img + "'>"))
}
示例12: PingServer
// Ping server
func (s *Client) PingServer() {
bytes, e := s._get(fmt.Sprintf("client/%s/ping?tags=%s&hostname=%s", url.QueryEscape(s.Id), url.QueryEscape(strings.Join(conf.GetTags(), ",")), url.QueryEscape(s.Hostname)))
if e == nil {
obj, jerr := jason.NewObjectFromBytes(bytes)
if jerr == nil {
status, statusE := obj.GetString("status")
serverInstanceId, _ := obj.GetString("server_instance_id")
// Ping failed, re-authenticate
if statusE != nil || status != "OK" {
log.Println(string(bytes))
log.Println("Re-authenticate with server")
s.AuthServer()
} else {
// Only log a connect if the instance ID changed
if len(s.ConnectedServerInstanceId) == 0 || s.ConnectedServerInstanceId != serverInstanceId {
s.ConnectedServerInstanceId = serverInstanceId
log.Println(fmt.Sprintf("Client registered with server %s", s.ConnectedServerInstanceId))
}
}
}
}
}
示例13: AuthServer
// Auth server, token is used for verifying commands
// @todo This function needs more logging in failure scenarios
func (s *Client) AuthServer() {
b, e := s._req("POST", fmt.Sprintf("client/%s/auth", url.QueryEscape(s.Id)), nil)
if e == nil {
obj, jerr := jason.NewObjectFromBytes(b)
if jerr == nil {
// Get signature
token, et := obj.GetString("token")
if et != nil || len(token) < 1 {
return
}
// Get token signatur
tokenSignature, ets := obj.GetString("token_signature")
if ets != nil || len(tokenSignature) < 1 {
return
}
// Verify token signature with our secure token
hasher := sha256.New()
hasher.Write([]byte(token))
hasher.Write([]byte(conf.Token))
expectedTokenSignature := base64.URLEncoding.EncodeToString(hasher.Sum(nil))
// The same?
if tokenSignature != expectedTokenSignature {
log.Println("ERROR! Token signature from server is invalid, communication between server and client might be tampered with")
return
}
// Store token if it is valid
s.mux.Lock()
s.AuthToken = token
s.mux.Unlock()
log.Printf("Client authenticated with server")
}
}
}
示例14: parseWhere
func (f *Filter) parseWhere(str string) (err error) {
where := &Where{}
f.where = where
if str == "" {
return
}
root, err := jason.NewObjectFromBytes([]byte(str))
if err != nil {
fmt.Println("parse json failed")
return err
}
oa, _ := root.GetObjectArray("$or")
if oa == nil {
c, err := parseCondition(root)
if err != nil {
fmt.Println("parseCondition failed")
return err
}
*where = append(*where, c)
} else {
for _, o := range oa {
c, err := parseCondition(o)
if err != nil {
fmt.Println("parseCondition failed")
return err
}
*where = append(*where, c)
}
}
return nil
}
示例15:
BeforeEach(func() {
ImportHoverflyRecords(jsonRequestResponsePair1)
ImportHoverflyRecords(jsonRequestResponsePair2)
ImportHoverflyRecords(jsonRequestResponsePairTemplate)
SetHoverflyResponseDelays("testdata/delays.json")
})
It("Should get all the Hoverfly simulation data in one JSON file", func() {
req := sling.New().Get(hoverflyAdminUrl + "/api/v2/simulation")
res := DoRequest(req)
Expect(res.StatusCode).To(Equal(200))
responseJson, err := ioutil.ReadAll(res.Body)
Expect(err).To(BeNil())
jsonObject, err := jason.NewObjectFromBytes(responseJson)
Expect(err).To(BeNil())
metaObject, err := jsonObject.GetObject("meta")
Expect(err).To(BeNil())
schemaVersion, err := metaObject.GetString("schemaVersion")
Expect(err).To(BeNil())
Expect(schemaVersion).To(Equal("v1"))
hoverflyVersion, err := metaObject.GetString("hoverflyVersion")
Expect(err).To(BeNil())
Expect(hoverflyVersion).ToNot(BeNil())
timeExported, err := metaObject.GetString("timeExported")
Expect(err).To(BeNil())
Expect(timeExported).ToNot(BeNil())
dataObject, err := jsonObject.GetObject("data")