当前位置: 首页>>代码示例>>Golang>>正文


Golang jason.NewObjectFromBytes函数代码示例

本文整理汇总了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
		}
	}
}
开发者ID:Shadey,项目名称:Leo,代码行数:29,代码来源:main.go

示例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)
	}
}
开发者ID:RobinUS2,项目名称:indispenso,代码行数:36,代码来源:client.go

示例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
}
开发者ID:coshx,项目名称:james,代码行数:35,代码来源:blog_post.go

示例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)

	}
}
开发者ID:SudeepParajuli,项目名称:instainer,代码行数:55,代码来源:instainer.go

示例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()
	}
}
开发者ID:qband,项目名称:down,代码行数:12,代码来源:benchmark_small_payload_test.go

示例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"

}
开发者ID:Vaultpls,项目名称:Telegram-Twitch-Bot,代码行数:14,代码来源:json.go

示例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,
	}
}
开发者ID:swapagarwal,项目名称:gojudge,代码行数:16,代码来源:helper.go

示例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()
	}
}
开发者ID:qband,项目名称:down,代码行数:16,代码来源:benchmark_medium_payload_test.go

示例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)
		}
	}

}
开发者ID:CiscoDevNet,项目名称:coding-skills-go,代码行数:45,代码来源:learning-labs-basics-step2.go

示例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
}
开发者ID:Vaultpls,项目名称:Telegram-Twitch-Bot,代码行数:19,代码来源:json.go

示例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 + "'>"))
}
开发者ID:pavanchokshi,项目名称:GO,代码行数:42,代码来源:FBoAuth.go

示例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))
				}
			}
		}
	}
}
开发者ID:RobinUS2,项目名称:indispenso,代码行数:24,代码来源:client.go

示例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")
		}
	}
}
开发者ID:RobinUS2,项目名称:indispenso,代码行数:39,代码来源:client.go

示例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
}
开发者ID:aiyi,项目名称:go,代码行数:37,代码来源:where.go

示例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")
开发者ID:SpectoLabs,项目名称:hoverfly,代码行数:30,代码来源:ft_api_test.go


注:本文中的github.com/antonholmquist/jason.NewObjectFromBytes函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。