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


Golang jsonq.NewQuery函数代码示例

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


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


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