本文整理汇总了Golang中github.com/jeffail/gabs.ParseJSON函数的典型用法代码示例。如果您正苦于以下问题:Golang ParseJSON函数的具体用法?Golang ParseJSON怎么用?Golang ParseJSON使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ParseJSON函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: SendRoomHistory
func (svc *Service) SendRoomHistory(so socketio.Socket, uid, room string, last int) {
v := svc.Rooms[room]
k := room
start := len(v.Messages) - last
if last == 0 || start < 0 {
start = 0
}
//send chat history
history := "{\"history\":["
for j := start; j < len(v.Messages); j++ {
history += v.Messages[j].String()
if j < len(v.Messages)-1 {
history += ","
}
}
history += "]}"
h, _ := gabs.ParseJSON([]byte("{}"))
m, _ := gabs.ParseJSON([]byte(history))
h.SetP(m.Path("history").Data(), "history")
h.SetP(k, "room")
h.SetP(v.FriendlyName, "name")
so.Emit("history", h.String())
}
开发者ID:pageben,项目名称:assemble-web-chat,代码行数:26,代码来源:service.go
示例2: JoinRoom
func (svc *Service) JoinRoom(so socketio.Socket, uid string, room string) {
v := svc.Rooms[room]
k := room
//check for permission
_, ok := v.MemberUIDs[uid]
if !ok {
return
}
so.Join(k)
jo, _ := gabs.ParseJSON([]byte("{}"))
jo.SetP(v.MaxExpTime.String(), "maxexptime")
jo.SetP(v.MinExpTime.String(), "minexptime")
jo.SetP(k, "room")
jo.SetP(v.FriendlyName, "name")
so.Emit("join", jo.String())
bc, _ := gabs.ParseJSON([]byte("{}"))
bc.SetP(svc.Users[uid].Token.Path("nick").Data().(string), "nick")
bc.SetP(uid, "uid")
bc.SetP(k, "room")
bc.SetP(v.FriendlyName, "name")
so.BroadcastTo(k, "joined", bc.String())
}
开发者ID:timbwhitt,项目名称:assemble-web-chat,代码行数:27,代码来源:service.go
示例3: TestPutStatementWithConflictID
func TestPutStatementWithConflictID(t *testing.T) {
m := martini.Classic()
sess, err := mgo.Dial(miscs.GlobalConfig.MongoDB.URL)
defer sess.Close()
if err != nil {
t.Fatalf("%v", err)
}
c := New(sess)
m.Put("/:user/:app/statements", c.StoreStatement)
stmt1, err := gabs.ParseJSON([]byte(singleStatement01))
if err != nil {
t.Fatal(err)
}
stmt2, err := gabs.ParseJSON([]byte(singleStatement02))
if err != nil {
t.Fatal(err)
}
// set same ID
statementID := uuid.NewV4().String()
_, err = stmt1.SetP(statementID, "id")
if err != nil {
t.Fatal(err)
}
_, err = stmt2.SetP(statementID, "id")
if err != nil {
t.Fatal(err)
}
// 1
resp := httptest.NewRecorder()
req, _ := http.NewRequest("PUT",
"/test/test/statements?statementId="+statementID,
strings.NewReader(stmt1.String()),
)
req.Header.Add("X-Experience-API-Version", "1.0.2")
m.ServeHTTP(resp, req)
if got, expected := resp.Code, http.StatusNoContent; got != expected {
t.Fatalf("Expected %v response code from put single statement; got %d", expected, got)
}
// 2
resp = httptest.NewRecorder()
req, _ = http.NewRequest("PUT",
"/test/test/statements?statementId="+statementID,
strings.NewReader(stmt2.String()),
)
req.Header.Add("X-Experience-API-Version", "1.0.2")
m.ServeHTTP(resp, req)
if got, expected := resp.Code, http.StatusConflict; got != expected {
t.Fatalf("Expected %v response code from put single statement; got %d", expected, got)
}
}
开发者ID:realglobe-Inc,项目名称:edo-xrs,代码行数:59,代码来源:statement_put_test.go
示例4: testGetMultStatementOfGroup
func testGetMultStatementOfGroup(t *testing.T, group *gabs.Container) {
db := initDatabase(t)
defer db.Close()
mart := initHandler(db)
ids := []string{
uuid.NewV4().String(),
uuid.NewV4().String(),
uuid.NewV4().String(),
uuid.NewV4().String(),
}
stmt, err := gabs.ParseJSON([]byte(statetmentAgentBoilerplate))
fatalIfError(t, err)
stmtSlice := []*gabs.Container{
appendAccount(t, stmt),
appendMbox(t, stmt),
appendMboxSHA1(t, stmt),
appendOpenID(t, stmt),
}
for i := 0; i < len(ids); i++ {
putStatement(t, mart, stmtSlice[i].String(), ids[i])
var s interface{}
err = json.Unmarshal([]byte(stmtSlice[i].Search("actor").String()), &s)
fatalIfError(t, err)
err = group.ArrayAppendP(s, "actor.member")
fatalIfError(t, err)
}
// construct query
v := &url.Values{}
//t.Log(group.Search("actor").String())
v.Add("agent", group.Search("actor").String())
resp := getStatement(t, mart, v)
//t.Log(string(resp))
respstmt, err := gabs.ParseJSON(resp)
fatalIfError(t, err)
cnt, err := respstmt.ArrayCount("statements")
fatalIfError(t, err)
if cnt != len(ids) {
t.Fatalf("Expected %d statements in response; got %d", len(ids), cnt)
}
children, err := respstmt.S("statements").Children()
fatalIfError(t, err)
for idx, stm := range children {
if id, ok := stm.Search("id").Data().(string); !ok || id != ids[idx] {
t.Fatalf("Got invalid order of statement array")
}
}
}
开发者ID:realglobe-Inc,项目名称:edo-xrs,代码行数:56,代码来源:statement_fetch_test.go
示例5: TestGetStatementWithCanonicalFormat
func TestGetStatementWithCanonicalFormat(t *testing.T) {
db := initDatabase(t)
defer db.Close()
mart := initHandler(db)
id1 := uuid.NewV4().String()
stmt, err := gabs.ParseJSON([]byte(singleStatementWithLangMap))
fatalIfError(t, err)
vsuffix := uuid.NewV4().String()
verbID := "http://example.com/realglobe/XAPIprofile/test-" + vsuffix
_, err = stmt.SetP(verbID, "verb.id")
fatalIfError(t, err)
putStatement(t, mart, stmt.String(), id1)
// construct query
v := &url.Values{}
v.Add("verb", verbID)
v.Add("format", "canonical")
respstmt, err := gabs.ParseJSON(getStatement(t, mart, v))
fatalIfError(t, err)
cnt, err := respstmt.ArrayCount("statements")
fatalIfError(t, err)
if cnt != 1 {
t.Fatalf("Expected 1 statements in response; got %d", cnt)
}
// check ID
s0, err := respstmt.ArrayElement(0, "statements")
fatalIfError(t, err)
if id, ok := s0.Search("id").Data().(string); !ok || id != id1 {
t.Fatalf("Got invalid statement")
}
// check LangMaps
scale, err := s0.ArrayElement(0, "object", "definition", "scale")
fatalIfError(t, err)
if _, ok := scale.Search("description", "ja-JP").Data().(string); !ok {
t.Fatalf("ja-JP field not found")
}
if _, ok := scale.Search("description", "en-US").Data().(string); ok {
t.Fatalf("en-US field is in response (not removed)")
}
if _, ok := s0.Search("object", "definition", "description", "ja-JP").Data().(string); !ok {
t.Fatalf("ja-JP field not found")
}
if _, ok := s0.Search("object", "definition", "description", "en-US").Data().(string); ok {
t.Fatalf("en-US field is in response (not removed)")
}
}
开发者ID:realglobe-Inc,项目名称:edo-xrs,代码行数:55,代码来源:statement_fetch_test.go
示例6: testGetMultStatementWithRelatedAgents
func testGetMultStatementWithRelatedAgents(t *testing.T, agent map[string]interface{}) {
db := initDatabase(t)
defer db.Close()
mart := initHandler(db)
id1 := uuid.NewV4().String()
id2 := uuid.NewV4().String()
stmt, err := gabs.ParseJSON([]byte(singleStatementWithMember))
fatalIfError(t, err)
dprefix := uuid.NewV4().String()
mailto := "mailto:[email protected]" + dprefix + ".realglobe.example.com"
_, err = stmt.SetP(mailto, "actor.mbox")
fatalIfError(t, err)
actor, err := gabs.Consume(agent)
fatalIfError(t, err)
err = stmt.ArrayAppendP(actor.Data(), "actor.member")
fatalIfError(t, err)
putStatement(t, mart, stmt.String(), id1)
putStatement(t, mart, stmt.String(), id2)
// construct query
v := &url.Values{}
v.Add("agent", actor.String())
v.Add("related_agents", "true")
respstmt, err := gabs.ParseJSON(getStatement(t, mart, v))
fatalIfError(t, err)
cnt, err := respstmt.ArrayCount("statements")
fatalIfError(t, err)
if cnt != 2 {
t.Fatalf("Expected 2 statements in response; got %d", cnt)
}
s0, err := respstmt.ArrayElement(0, "statements")
fatalIfError(t, err)
if id, ok := s0.Search("id").Data().(string); !ok || id != id1 {
t.Fatalf("Got invalid order of statement array")
}
s1, err := respstmt.ArrayElement(1, "statements")
fatalIfError(t, err)
if id, ok := s1.Search("id").Data().(string); !ok || id != id2 {
t.Fatalf("Got invalid order of statement array")
}
}
开发者ID:realglobe-Inc,项目名称:edo-xrs,代码行数:50,代码来源:statement_fetch_test.go
示例7: MachineSshKey
func MachineSshKey(machine string) string {
// StorePath has changed in docker-machine 0.5, switch accordingly.
machineInfo, machineErr := RunMachineCommand("inspect", machine)
if machineErr != nil {
LogError(machineErr.Error())
}
infoJson, infoErr := gabs.ParseJSON([]byte(machineInfo))
if infoErr != nil {
LogError("could not load machine info from `docker-machine`.")
}
// Docker Machine 0.5.1 has a direct key.
storepath, ok := infoJson.Path("Driver.Driver.SSHKeyPath").Data().(string)
if ok {
return storepath
}
// Docker Machine 0.5 has it in a sub-folder.
storepath, ok = infoJson.Path("Driver.StorePath").Data().(string)
if ok {
return storepath + "/machines/" + infoJson.Path("Driver.MachineName").Data().(string) + "/id_rsa"
}
storepath, ok = infoJson.Path("StorePath").Data().(string)
if !ok {
LogError("could not determine SSH key path from `docker-machine`.")
}
return storepath + "/id_rsa"
}
开发者ID:chinthakagodawita,项目名称:docker-unisync,代码行数:32,代码来源:machine.go
示例8: request
func request(ip string, url string) (*gabs.Container, error) {
var data *gabs.Container
url = fmt.Sprintf(url, ip)
resp, err := http.Get(url)
if err != nil {
return data, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return data, err
}
jsonbody, err := gabs.ParseJSON(body)
if err != nil {
fmt.Println(err.Error())
fmt.Println("gets data is not JSON structure")
fmt.Println(string(body))
os.Exit(0)
// return data, err
}
return jsonbody, nil
}
开发者ID:sg3des,项目名称:whois,代码行数:25,代码来源:whois.go
示例9: Parse
func (*ParserUnive) Parse() ([]Library, error) {
url := "http://static.unive.it/sitows/index/personebiblioteche"
res, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
json, _ := gabs.ParseJSON(body)
children, _ := json.ChildrenMap()
libraries := []Library{}
for key, child := range children {
takenPlaces, _ := strconv.Atoi(child.Search("persone").Data().(string))
totalPlaces, _ := strconv.Atoi(child.Search("max").Data().(string))
library := Library{
MappingID: key,
TakenPlaces: takenPlaces,
TotalPlaces: totalPlaces,
}
libraries = append(libraries, library)
}
return libraries, nil
}
开发者ID:philipgiuliani,项目名称:libraries,代码行数:28,代码来源:parser_unive.go
示例10: parseAnswear
func parseAnswear(answear string) {
m := Main{}
p := Parametr{}
mainItem := make([]Item, 0)
jsonParsed, err := gabs.ParseJSON([]byte(answear))
if err != nil {
return
}
p.parametr = jsonParsed.Search("main", "param", "param").Data().([]interface{})[0].(string)
p.typeParametr = jsonParsed.Search("main", "param", "t").Data().([]interface{})[0].(string)
//childreItem - items for key "i"
childrenItem, _ := jsonParsed.Search("main", "i").Children()
//children - array with main key "i"
children := childrenItem[0]
//resultChildren - final array with our keys "p","t","ti"
resultChildren, _ := children.Children()
var item Item
for _, child := range resultChildren {
item.parametr = child.Data().(map[string]interface{})["p"].(string)
item.typeItem = child.Data().(map[string]interface{})["t"].(string)
item.title = child.Data().(map[string]interface{})["ti"].(string)
mainItem = append(mainItem, item)
}
m.items = mainItem
m.parametr = p
fmt.Println(m)
}
开发者ID:podliy16,项目名称:gogogog,代码行数:33,代码来源:parseAnswears.go
示例11: jsonSocketWrapper
func jsonSocketWrapper(so socketio.Socket, checkUser bool, f soHandlerJSON) soHandler {
return soHandler(func(msg string) {
defer func() {
if err := recover(); err != nil {
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
log.Printf("socket error %v: %s", err, buf)
}
}()
g, err := gabs.ParseJSON([]byte(msg))
if err != nil {
log.Println(err)
return
}
uid := ""
ok := false
if checkUser {
uid, ok = service.ExtractAndCheckToken(so, g)
if !ok {
return
}
service.Users[uid].LastAct = time.Now()
}
f(uid, g)
})
}
开发者ID:pageben,项目名称:assemble-web-chat,代码行数:30,代码来源:assemble.go
示例12: NewSensor
func NewSensor(wg sync.WaitGroup, sensor *MPSensor) {
defer wg.Done()
hkSwitch := GetHKSwitch(sensor)
hkSwitch.ticker = time.NewTicker(30 * time.Second)
for {
<-hkSwitch.ticker.C
log.Printf("[INFO] Updating %s", hkSwitch.accessory.Info.Name.GetValue())
urlString := fmt.Sprintf("http://%s/sensors/%d", viper.GetString("Host"), hkSwitch.sensor.port)
req, _ := newRequest("GET", urlString, nil)
res, _ := client.Do(req)
defer res.Body.Close()
jsonBytes, _ := ioutil.ReadAll(res.Body)
jsonParsed, _ := gabs.ParseJSON(jsonBytes)
output := jsonParsed.Path("sensors").Index(0).Path("output").Data().(float64) != 0
hkSwitch.sensor.output = output
hkSwitch.accessory.Switch.On.SetValue(output)
}
}
开发者ID:Pmaene,项目名称:hkmpower,代码行数:25,代码来源:hkmpowerd.go
示例13: Connect
func Connect() {
var wg sync.WaitGroup
authenticate()
urlString := fmt.Sprintf("http://%s/sensors", viper.GetString("Host"))
req, _ := newRequest("GET", urlString, nil)
res, _ := client.Do(req)
defer res.Body.Close()
jsonBytes, _ := ioutil.ReadAll(res.Body)
jsonParsed, _ := gabs.ParseJSON(jsonBytes)
children, _ := jsonParsed.Search("sensors").Children()
wg.Add(len(children))
for _, child := range children {
port := uint8(child.Path("port").Data().(float64))
output := child.Path("output").Data().(float64) != 0
log.Printf("[INFO] Discovered Sensor %d", port)
sensor := &MPSensor{port, output}
go NewSensor(wg, sensor)
}
wg.Wait()
}
开发者ID:Pmaene,项目名称:hkmpower,代码行数:27,代码来源:hkmpowerd.go
示例14: makePrice
// The markup contains a JSON object with all the data for Bloomberg's page
// and it is all on one line, so here I split the markup up into lines,
// scan until find the one that has the variable in it, chop off the start
// of the line which leaves just the JSON object which I can then parse
// and extract the useful data from.
func (this bloomberg) makePrice(markup string) entities.Price {
for _, line := range strings.Split(markup, "\n") {
if strings.Index(line, "bootstrappedData: ") > -1 {
jsonv := []byte(line[18:len(line)])
jsonParsed, err := gabs.ParseJSON(jsonv)
if err != nil {
fmt.Fprintln(os.Stderr, "Could not parse the Bloomberg page: ", err)
os.Exit(1)
}
children, ok := jsonParsed.Children()
if ok != nil {
fmt.Fprintln(os.Stderr, "Could not parse the Bloomberg page")
os.Exit(1)
}
for _, child := range children {
if !child.Exists("basicQuote", "price") {
continue
}
price := child.Path("basicQuote.price").Data().(float64)
date := child.Path("basicQuote.priceDate").Data().(string)
parsedDate, _ := time.Parse("1/2/2006", date)
timed := child.Path("basicQuote.priceTime").Data().(string)
parsedTime, _ := time.Parse("3:04 PM", timed)
newPrice := entities.NewPrice(parsedDate, parsedTime, string(this),
strconv.FormatFloat(price, 'f', -1, 64),
)
return newPrice
}
}
}
return entities.Price{}
}
开发者ID:Fepelus,项目名称:getPrices,代码行数:37,代码来源:bloomberg.go
示例15: init
func init() {
/* Initialise configuration instance, w/ GABS. */
log.Debug("Initialise configuration instance")
// This has to be a absolute path.
configurationPath := os.Getenv("RESTAPI_CONFIG")
// Ascertain if the configuration path is inputted.
log.Debug("Testing if the configuration path is inputted.")
if _, err := os.Stat(configurationPath); os.IsNotExist(err) {
log.Crit("The configuration file does not exist!",
log.Ctx{"File": configurationPath})
os.Exit(1)
}
log.Debug("Reading configuration file into RAM.")
configurationFile, err := ioutil.ReadFile(configurationPath)
if err != nil {
log.Error("The JSON config could not be loaded..",
log.Ctx{"Error": err.Error()})
os.Exit(1)
}
log.Debug("Parsing configuration file into a GABS instance.")
config, err = gabs.ParseJSON(configurationFile)
if err != nil {
log.Error("The JSON config could not be parsed.",
log.Ctx{"Error": err.Error()})
os.Exit(1)
}
/* Finish initializing the configuration instance */
}
开发者ID:ObamaPhony,项目名称:rest-api,代码行数:35,代码来源:api.go
示例16: hbuser
func hbuser(user string) {
resp, err := http.Get("http://hummingbird.me/api/v1/users/" + user)
if err != nil {
message <- "Request Error"
}
defer resp.Body.Close()
res, err := ioutil.ReadAll(resp.Body)
if err != nil {
message <- "Request Error"
}
jsn, _ := gabs.ParseJSON(res)
name := jsn.S("name").Data()
if name == nil {
name = "?"
}
life := jsn.S("life_spent_on_anime").Data()
if life == nil {
life = "0"
}
last := jsn.S("last_library_update").Data()
if last == nil {
last = "?"
}
message <- name.(string) + ": Time spent watching anime: " + strconv.FormatFloat(life.(float64)/60/24/30, 'f', 2, 64) + " months. Last Update: " + last.(string)
}
开发者ID:XAMPP,项目名称:Gakin,代码行数:26,代码来源:main.go
示例17: pollMessage
func pollMessage(queueUrl string) {
sqsClient := sqs.New(&aws.Config{Region: aws.String("us-east-1")})
req := &sqs.ReceiveMessageInput{QueueURL: aws.String(queueUrl)}
result, err := sqsClient.ReceiveMessage(req)
if nil != err {
panic(err)
} else {
parsedResponse, err := gabs.ParseJSON([]byte(*result.Messages[0].Body))
if nil != err {
panic(err)
}
var payload string
payload = parsedResponse.Path("Message").Data().(string)
fmt.Println(unpretty(payload))
deleteRequest := &sqs.DeleteMessageInput{QueueURL: aws.String(queueUrl), ReceiptHandle: aws.String(*result.Messages[0].ReceiptHandle)}
_, err = sqsClient.DeleteMessage(deleteRequest)
if nil != err {
panic(err)
}
}
}
开发者ID:exceleratesystems,项目名称:sqstail,代码行数:31,代码来源:main.go
示例18: main
func main() {
// Load config
file, err := os.Open("gakin.json")
if err != nil {
fmt.Printf("[*] Unable to load config: %s\n", err.Error())
}
cfg, err := ioutil.ReadAll(file)
if err != nil {
fmt.Printf("[*] Configure error: %s\n", err.Error())
}
r, err := gabs.ParseJSON(cfg)
if err != nil {
fmt.Printf("[*] Configure error: %s\n", err.Error())
}
messages = make(map[string]string)
sauce_key = r.S("sauce_key").Data().(string)
irchndl, _ := r.S("irc").Children()
for _, icon := range irchndl {
server, _ := icon.S("server").Data().(string)
channel, _ := icon.S("channel").Data().(string)
nickname, _ := icon.S("nickname").Data().(string)
go IRCConnection(server, channel, nickname)
}
http.HandleFunc("/", HandlePost)
endpoint, _ := r.S("endpoint").Data().(string)
http.ListenAndServe(endpoint, nil)
}
开发者ID:XAMPP,项目名称:Gakin,代码行数:35,代码来源:main.go
示例19: BroadcastUserLeave
func (svc *Service) BroadcastUserLeave(room string, uid string, so socketio.Socket) {
bc, _ := gabs.ParseJSON([]byte("{}"))
bc.SetP(svc.Users[uid].Token.Path("uid").Data().(string), "uid")
bc.SetP(room, "room")
so.BroadcastTo(room, "leave", bc.String())
so.Emit("leave", bc.String())
}
开发者ID:timbwhitt,项目名称:assemble-web-chat,代码行数:7,代码来源:service.go
示例20: parseMapFile
func parseMapFile(filePath string) *Map {
mapData, err := ioutil.ReadFile(filePath)
if err != nil {
log.Fatal(err)
}
jsonParsed, err := gabs.ParseJSON(mapData)
if err != nil {
log.Fatal(err)
}
mapWidth := int(jsonParsed.Path("width").Data().(float64))
// Only first layer from Tiled data is used, rest ignored
firstMapLayer := jsonParsed.Search("layers", "data").Index(0)
tileTypes, _ := firstMapLayer.Children()
m := Map{}
for index, tileType := range tileTypes {
x, y := calcTileCoords(index, mapWidth)
tile := Tile{X: x, Y: y, Type: int(tileType.Data().(float64))}
m.addTile(&tile)
}
return &m
}
开发者ID:oskarer,项目名称:pathfinder-go,代码行数:25,代码来源:map.go
注:本文中的github.com/jeffail/gabs.ParseJSON函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论