• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang jsonq.NewQuery函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/jmoiron/jsonq.NewQuery函数的典型用法代码示例。如果您正苦于以下问题:Golang NewQuery函数的具体用法?Golang NewQuery怎么用?Golang NewQuery使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了NewQuery函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: parseAlbums

func (p *PicasaAPI) parseAlbums(js interface{}) ([]*PicasaAlbum, error) {
	jq := jsonq.NewQuery(js)
	entries, _ := jq.Array("feed", "entry")
	albums := make([]*PicasaAlbum, len(entries))

	for i, entry := range entries {
		eq := jsonq.NewQuery(entry)
		album := new(PicasaAlbum)
		album.ApiUrl, _ = eq.String("id", "$t")
		album.AlbumId, _ = eq.String("gphoto$id", "$t")
		album.Published, _ = eq.String("published", "$t")
		album.Updated, _ = eq.String("updated", "$t")
		album.Title, _ = eq.String("title", "$t")
		album.Summary, _ = eq.String("summary", "$t")
		album.Rights, _ = eq.String("gphoto$access", "$t")
		album.NumPhotos, _ = eq.Int("gphoto$numphotos", "$t")
		links, _ := eq.Array("link")
		for _, link := range links {
			lq := jsonq.NewQuery(link)
			s, err := lq.String("href")
			if err != nil {
				continue
			}
			album.Links = append(album.Links, s)
		}
		album.AlbumType, _ = eq.String("gphoto$albumType", "$t")
		album.Thumbnail, _ = eq.String("media$group", "media$thumbnail", "0", "url")
		albums[i] = album
	}
	return albums, nil
}
开发者ID:jseaidou,项目名称:monet,代码行数:31,代码来源:picasa.go


示例2: parsePhotos

func (p *PicasaAPI) parsePhotos(js interface{}) ([]*PicasaPhoto, error) {
	jq := jsonq.NewQuery(js)
	entries, _ := jq.Array("feed", "entry")
	photos := make([]*PicasaPhoto, len(entries))

	for i, entry := range entries {
		eq := jsonq.NewQuery(entry)
		photo := new(PicasaPhoto)
		photo.ApiUrl, _ = eq.String("id", "$t")
		photo.PhotoId, _ = eq.String("gphoto$id", "$t")
		photo.AlbumId, _ = eq.String("gphoto$albumid", "$t")
		photo.Published, _ = eq.String("published", "$t")
		photo.Updated, _ = eq.String("updated", "$t")
		photo.Title, _ = eq.String("title", "$t")
		photo.Summary, _ = eq.String("summary", "$t")
		photo.Rights, _ = eq.String("gphoto$access", "$t")
		links, _ := eq.Array("link")
		for _, link := range links {
			lq := jsonq.NewQuery(link)
			s, err := lq.String("href")
			if err != nil {
				continue
			}
			photo.Links = append(photo.Links, s)
		}
		photo.Height, _ = eq.Int("gphoto$height", "$t")
		photo.Width, _ = eq.Int("gphoto$width", "$t")
		photo.Size, _ = eq.Int("gphoto$size", "$t")

		photo.Large.Url, _ = eq.String("media$group", "media$content", "0", "url")
		photo.Large.Height, _ = eq.Int("media$group", "media$content", "0", "height")
		photo.Large.Width, _ = eq.Int("media$group", "media$content", "0", "width")

		photo.Position, _ = eq.Int("gphoto$position", "$t")

		thumbnails, _ := eq.Array("media$group", "media$thumbnail")
		for _, thumb := range thumbnails {
			tq := jsonq.NewQuery(thumb)
			t := Image{}
			t.Url, _ = tq.String("url")
			t.Height, _ = tq.Int("height")
			t.Width, _ = tq.Int("width")
			photo.Thumbnails = append(photo.Thumbnails, t)
		}

		photo.ExifTags = map[string]string{}

		tags, _ := eq.Object("exif$tags")
		for key, obj := range tags {
			oq := jsonq.NewQuery(obj)
			photo.ExifTags[key], _ = oq.String("$t")
		}

		photos[i] = photo
	}
	return photos, nil
}
开发者ID:jseaidou,项目名称:monet,代码行数:57,代码来源:picasa.go


示例3: getCord

func getCord(address, city, state, zip string) (lat, lng float64) {
	// request http api
	res, err := http.Get(strings.Replace("http://maps.google.com/maps/api/geocode/json?address="+address+",+"+city+",+"+state+",+"+zip+"&sensor=false", " ", "+", -1))
	if err != nil {
		log.Fatal(err)
	}

	body, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		log.Fatal(err)
	}

	if res.StatusCode != 200 {
		log.Fatal("Unexpected status code", res.StatusCode)
	}
	data := map[string]interface{}{}
	dec := json.NewDecoder(strings.NewReader(string(body)))
	err = dec.Decode(&data)
	if err != nil {
		fmt.Println(err)
	}
	jq := jsonq.NewQuery(data)

	lat, err = jq.Float("results", "0", "geometry", "location", "lat")
	if err != nil {
		fmt.Println(err)
	}

	lng, err = jq.Float("results", "0", "geometry", "location", "lng")
	if err != nil {
		fmt.Println(err)
	}
	return
}
开发者ID:nsushain90,项目名称:cmpe273-assignment2,代码行数:35,代码来源:assignment-2.go


示例4: pricetoBegin

func pricetoBegin(x string) (y Data) {
	var price []int
	response, err := http.Get(x)
	if err != nil {
		return
	}
	defer response.Body.Close()
	resp := make(map[string]interface{})
	body, _ := ioutil.ReadAll(response.Body)
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return
	}
	ptr := resp["prices"].([]interface{})
	jq := jsonq.NewQuery(resp)
	for i, _ := range ptr {
		pr, _ := jq.Int("prices", fmt.Sprintf("%d", i), "low_estimate")
		price = append(price, pr)
	}
	min := price[0]
	for j, _ := range price {
		if price[j] <= min && price[j] != 0 {
			min = price[j]
		}
	}
	du, _ := jq.Int("prices", "0", "duration")
	dist, _ := jq.Float("prices", "0", "distance")
	d := Data{
		id:       "",
		price:    min,
		duration: du,
		distance: dist,
	}
	return d
}
开发者ID:aditya-dhende,项目名称:cmpe273-assignment3,代码行数:35,代码来源:assignment3.go


示例5: getCrittercismOAuthToken

// getCrittercismOAuthToken fetches a new OAuth Token from the Crittercism API given a username and password
func getCrittercismOAuthToken(login, password string) (token string, expires int, err error) {
	var params = fmt.Sprintf(`{"login": "%s", "password": "%s"}}`, login, password)

	// Construct REST Request
	url := fmt.Sprintf("%s/token", crittercismAPIURL)
	p := []byte(params)
	client := &http.Client{}
	req, _ := http.NewRequest("POST", url, bytes.NewBuffer(p))
	req.Header.Set("Content-Type", "application/json")

	// Make Request
	if resp, err := client.Do(req); err == nil {
		defer resp.Body.Close()

		// Parse JSON
		if body, err := ioutil.ReadAll(resp.Body); err == nil {
			data := map[string]interface{}{}
			dec := json.NewDecoder(strings.NewReader(string(body)))
			dec.Decode(&data)
			jq := jsonq.NewQuery(data)

			// Parse out the token
			token, _ := jq.String("access_token")
			expires, _ := jq.Int("expires")
			return token, expires, nil

		} else {
			return "", 0, err // Parse Error
		}

	} else {
		return "", 0, err // Request Error
	}
}
开发者ID:andrewmlevy,项目名称:agent_crittercism,代码行数:35,代码来源:api.go


示例6: NewSong

// NewSong creates a track and adds to the queue
func (mc Mixcloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offset int) (Song, error) {
	title, _ := trackData.String("name")
	id, _ := trackData.String("slug")
	duration, _ := trackData.Int("audio_length")
	url, _ := trackData.String("url")
	thumbnail, err := trackData.String("pictures", "large")
	if err != nil {
		// Song has no artwork, using profile avatar instead
		userObj, _ := trackData.Object("user")
		thumbnail, _ = jsonq.NewQuery(userObj).String("pictures", "thumbnail")
	}

	song := &AudioTrack{
		id:        id,
		title:     title,
		url:       url,
		thumbnail: thumbnail,
		submitter: user,
		duration:  duration,
		offset:    offset,
		format:    "best",
		skippers:  make([]string, 0),
		dontSkip:  false,
		service:   mc,
	}
	return song, nil
}
开发者ID:DudeofA,项目名称:jewbot,代码行数:28,代码来源:service_mixcloud.go


示例7: GetItemName

// GetItemName returns the name of a given id in the language provided
func (c *Census) GetItemName(id int, lang string) string {
	tmp := map[string]interface{}{}
	url := fmt.Sprintf("%vget/%v/item/?item_id=%v", BaseURL, c.namespace, id)
	if err := decodeURL(url, &tmp); err != nil {
		return err.Error()
	}
	jq := jsonq.NewQuery(tmp)
	a, _ := jq.ArrayOfObjects("item_list")
	item := a[0]
	q := jsonq.NewQuery(item)
	if lang == "" {
		lang = "en"
	}
	s, _ := q.String("name", lang)
	return s
}
开发者ID:THUNDERGROOVE,项目名称:census,代码行数:17,代码来源:item.go


示例8: WSMain

func (c *Home) WSMain(in *goboots.In) *goboots.Out {

	defer in.Wsock.Close()

	type Resp struct {
		Success bool        `json:"success"`
		Error   string      `json:"error"`
		Kind    string      `json:"kind"`
		Payload interface{} `json:"payload"`
	}

	for {
		in.Wsock.SetWriteDeadline(time.Now().Add(time.Hour))
		in.Wsock.SetReadDeadline(time.Now().Add(time.Hour))
		raw := make(map[string]interface{})
		log.Println("[ws] will read msg")
		err := in.Wsock.ReadJSON(&raw)
		if err != nil {
			log.Println("[ws] error", err)
			return nil
		}
		q := jsonq.NewQuery(raw)
		kind, _ := q.String("kind")
		if kind == "top" {
			in.Wsock.WriteJSON(&Resp{true, "", "top", utils.GetLastTop()})
		}
	}
	return nil
}
开发者ID:gabstv,项目名称:overview,代码行数:29,代码来源:Home.go


示例9: makeQuery

func makeQuery(msg []byte) *jsonq.JsonQuery {
	data := map[string]interface{}{}
	dec := json.NewDecoder(bytes.NewReader(msg))
	dec.Decode(&data)
	jq := jsonq.NewQuery(data)
	return jq
}
开发者ID:BisnodeInformatics,项目名称:logspout-redis-logstash,代码行数:7,代码来源:redis_test.go


示例10: HTTPGetJSON

func (c *Context) HTTPGetJSON(url string) (*jsonq.JsonQuery, error) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Accept", "application/json")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode >= 300 {
		return nil, fmt.Errorf("%v: returned %v", url, resp.Status)
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	data := make(map[string]interface{})
	err = json.Unmarshal(body, &data)
	if err != nil {
		return nil, err
	}
	return jsonq.NewQuery(data), nil
}
开发者ID:noblehng,项目名称:bosun,代码行数:26,代码来源:template.go


示例11: initCommandFromSession

func (l *localExecDriver) initCommandFromSession() error {
	if l.session == nil {
		return fmt.Errorf("localexec: unable to init command with nil session")
	}

	// Fetch all the values first
	jq := jsonq.NewQuery(l.session.Profile().GetParams())
	name, err := jq.String("command", "name")
	if err != nil {
		return err
	}
	args, err := jq.ArrayOfStrings("command", "args")
	if err != nil {
		return err
	}

	// Sanity checks
	if name == "" {
		return fmt.Errorf("localexec: profile param error: empty command")
	}

	l.cmd = exec.Command(name)
	if args != nil && len(args) > 0 {
		l.cmd.Args = append(l.cmd.Args, args...)
	}

	log.Printf("localexec: session assigned with command %v", l.cmd)
	return nil
}
开发者ID:zer0her0,项目名称:gatewayd,代码行数:29,代码来源:driver.go


示例12: NotifyMarathonHandler

func (p *Resource) NotifyMarathonHandler(req *restful.Request, resp *restful.Response) {
	logrus.Infof("NotifyMarathonHandler is called!")

	dat, err := ioutil.ReadAll(req.Request.Body)

	if err != nil {
		logrus.Errorf("read notification body failed, error is %v", err)
		return
	}

	s := string(dat[:len(dat)])

	jsondata := map[string]interface{}{}
	result := json.NewDecoder(strings.NewReader(s))
	result.Decode(&jsondata)
	jq := jsonq.NewQuery(jsondata)
	value, _ := jq.String("eventType")
	logrus.Infof("Marathon callback starting ......................")
	logrus.Infof("Notification is %s", s)
	logrus.Infof("eventType is %s", value)

	res := response.Response{Success: true}
	resp.WriteEntity(res)
	return
}
开发者ID:popsuper1982,项目名称:DCOS_Cluster,代码行数:25,代码来源:marathonHandler.go


示例13: PerformGetRequest

// PerformGetRequest does all the grunt work for HTTPS GET request.
func PerformGetRequest(url string) (*jsonq.JsonQuery, error) {
	jsonString := ""

	if response, err := http.Get(url); err == nil {
		defer response.Body.Close()
		if response.StatusCode == 200 {
			if body, err := ioutil.ReadAll(response.Body); err == nil {
				jsonString = string(body)
			}
		} else {
			if response.StatusCode == 403 {
				return nil, errors.New("Invalid API key supplied.")
			}
			return nil, errors.New("Invalid ID supplied.")
		}
	} else {
		return nil, errors.New("An error occurred while receiving HTTP GET response.")
	}

	jsonData := map[string]interface{}{}
	decoder := json.NewDecoder(strings.NewReader(jsonString))
	decoder.Decode(&jsonData)
	jq := jsonq.NewQuery(jsonData)

	return jq, nil
}
开发者ID:DudeofA,项目名称:jewbot,代码行数:27,代码来源:youtube_dl.go


示例14: Mkdir

func (self *Baidu) Mkdir(path string) error {
	url := fmt.Sprintf("https://pcs.baidu.com/rest/2.0/pcs/file?method=mkdir&access_token=%s", self.token.AccessToken)
	url += "&path=" + neturl.QueryEscape(fmt.Sprintf("/apps/%s/%s", self.dir, path))

	buf := new(bytes.Buffer)
	form := multipart.NewWriter(buf)
	form.Close()
	resp, err := self.client.Post(url, form.FormDataContentType(), buf)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	buf.Reset()
	_, err = io.Copy(buf, resp.Body)
	if err != nil {
		return errors.New("response body read error")
	}
	respBody := make(map[string]interface{})
	err = json.NewDecoder(buf).Decode(&respBody)
	if err != nil {
		return errors.New("return json decode error")
	}
	q := jsonq.NewQuery(respBody)
	if resp.StatusCode != http.StatusOK {
		errCode, _ := q.Int("error_code")
		errMsg, _ := q.String("error_msg")
		return errors.New(fmt.Sprintf("server error %d %s", errCode, errMsg))
	}
	return nil
}
开发者ID:reusee,项目名称:FileStore,代码行数:31,代码来源:backend_baidu.go


示例15: CreateGroup

func (m *MarathonService) CreateGroup(payload []byte, marathonEndpoint string) (deploymentId string, err error) {
	url := strings.Join([]string{"http://", marathonEndpoint, "/v2/groups"}, "")
	logrus.Debugf("start to post group json %b to marathon %v", string(payload), marathonEndpoint)
	resp, err := httpclient.Http_post(url, string(payload),
		httpclient.Header{"Content-Type", "application/json"})
	if err != nil {
		logrus.Errorf("post group to marathon failed, error is %v", err)
		return
	}
	defer resp.Body.Close()

	// if response status is greater than 400, means marathon returns error
	// else parse body, findout deploymentId, and return
	data, _ := ioutil.ReadAll(resp.Body)
	if resp.StatusCode >= 400 {
		logrus.Errorf("marathon returned error code is %v", resp.StatusCode)
		logrus.Errorf("detail is %v", string(data))
		err = errors.New(string(data))
		return
	}

	// Parse data: marathon json data
	jsondata := map[string]interface{}{}
	result := json.NewDecoder(strings.NewReader(string(data)))
	result.Decode(&jsondata)
	jq := jsonq.NewQuery(jsondata)
	deploymentId, err = jq.String("deploymentId")
	return
}
开发者ID:popsuper1982,项目名称:DCOS_Cluster,代码行数:29,代码来源:marathonservice.go


示例16: Request

func (c *CrittercismAPIClient) Request(method, path string, params *CrittercismAPIParams) (jq *jsonq.JsonQuery, outErr error) {
	c.RawRequest(
		method,
		path,
		params,
		func(resp *http.Response, err error) {
			if resp != nil && resp.Body != nil {
				defer resp.Body.Close()
			}

			if err != nil {
				outErr = err
				return
			}

			// Parse Body
			if body, outErr := ioutil.ReadAll(resp.Body); outErr == nil {
				data := map[string]interface{}{}
				dec := json.NewDecoder(strings.NewReader(string(body)))
				dec.Decode(&data)
				jq = jsonq.NewQuery(data)
			}
		},
	)

	return jq, outErr
}
开发者ID:andrewmlevy,项目名称:agent_crittercism,代码行数:27,代码来源:api.go


示例17: NewSong

// NewSong creates a track and adds to the queue
func (sc SoundCloud) NewSong(user *gumble.User, trackData *jsonq.JsonQuery, offset int, playlist Playlist) (Song, error) {
	title, _ := trackData.String("title")
	id, _ := trackData.Int("id")
	durationMS, _ := trackData.Int("duration")
	url, _ := trackData.String("permalink_url")
	thumbnail, err := trackData.String("artwork_url")
	if err != nil {
		// Song has no artwork, using profile avatar instead
		userObj, _ := trackData.Object("user")
		thumbnail, _ = jsonq.NewQuery(userObj).String("avatar_url")
	}

	song := &AudioTrack{
		id:        strconv.Itoa(id),
		title:     title,
		url:       url,
		thumbnail: thumbnail,
		submitter: user,
		duration:  durationMS / 1000,
		offset:    offset,
		format:    "mp3",
		playlist:  playlist,
		skippers:  make([]string, 0),
		dontSkip:  false,
		service:   sc,
	}
	return song, nil
}
开发者ID:hpincket,项目名称:mumbledjkhaled,代码行数:29,代码来源:service_soundcloud.go


示例18: NewReader

func (self *Baidu) NewReader(length int, hash string) (io.Reader, hashbin.Callback, error) {
	path := neturl.QueryEscape(fmt.Sprintf("/apps/%s/%s/%d-%s", self.dir, hash[:2], length, hash))
	url := fmt.Sprintf("https://d.pcs.baidu.com/rest/2.0/pcs/file?method=download&access_token=%s&path=%s", self.token.AccessToken, path)
	resp, err := self.client.Get(url)
	if err != nil {
		return nil, nil, errors.New(fmt.Sprintf("get error: %s", url))
	}
	if resp.StatusCode != http.StatusOK {
		buf := new(bytes.Buffer)
		_, err = io.Copy(buf, resp.Body)
		if err != nil {
			return nil, nil, errors.New("response body read error")
		}
		respBody := make(map[string]interface{})
		err = json.NewDecoder(buf).Decode(&respBody)
		if err != nil {
			return nil, nil, errors.New("return json decode error")
		}
		q := jsonq.NewQuery(respBody)
		errCode, _ := q.Int("error_code")
		errMsg, _ := q.String("error_msg")
		return nil, nil, errors.New(fmt.Sprintf("fetch error %d %s", errCode, errMsg))
	}
	return resp.Body, func(err error) error {
		defer resp.Body.Close()
		if err != nil {
			return err
		}
		return nil
	}, nil
}
开发者ID:reusee,项目名称:FileStore,代码行数:31,代码来源:backend_baidu.go


示例19: createLocation

func createLocation(rw http.ResponseWriter, req *http.Request, p httprouter.Params) {
	var u Uberdata
	URL := "http://maps.google.com/maps/api/geocode/json?address="

	json.NewDecoder(req.Body).Decode(&u)

	u.Id = bson.NewObjectId()

	URL = URL + u.Address + " " + u.City + " " + u.State + " " + u.Zip + "&sensor=false"
	URL = strings.Replace(URL, " ", "+", -1)
	fmt.Println("url is: " + URL)

	response, err := http.Get(URL)
	if err != nil {
		return
	}
	defer response.Body.Close()

	resp := make(map[string]interface{})
	body, _ := ioutil.ReadAll(response.Body)
	err = json.Unmarshal(body, &resp)
	if err != nil {
		return
	}

	jq := jsonq.NewQuery(resp)
	status, err := jq.String("status")
	fmt.Println(status)
	if err != nil {
		return
	}
	if status != "OK" {
		err = errors.New(status)
		return
	}

	lat, err := jq.Float("results", "0", "geometry", "location", "lat")
	if err != nil {
		fmt.Println(err)
		return
	}
	lng, err := jq.Float("results", "0", "geometry", "location", "lng")
	if err != nil {
		fmt.Println(err)
		return
	}

	u.Coordinate.Lat = lat
	u.Coordinate.Lng = lng

	newSession().DB("tripplan").C("location").Insert(u)

	reply, _ := json.Marshal(u)

	rw.Header().Set("Content-Type", "application/json")
	rw.WriteHeader(201)
	fmt.Fprintf(rw, "%s", reply)

}
开发者ID:aditya-dhende,项目名称:cmpe273-assignment3,代码行数:59,代码来源:assignment3.go


示例20: fromJson

func fromJson(js string) *jsonq.JsonQuery {
	// usage: var, err := fromJson(json).String("value", "nestedvalue", "somearray, "0")
	data := map[string]interface{}{}
	dec := json.NewDecoder(strings.NewReader(js))
	dec.Decode(&data)
	jq := jsonq.NewQuery(data)
	return jq
}
开发者ID:JonathanUsername,项目名称:slack_markov,代码行数:8,代码来源:slack_markov.go



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang jsonq.JsonQuery类代码示例发布时间:2022-05-23
下一篇:
Golang common.NewJob函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap