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


Golang json.Marshal函数代码示例

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


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

示例1: Regenerate

// Regenerate user's auth tokens.
func Regenerate(c *client.Client, username string, all bool) (string, error) {
	var reqBody []byte
	var err error

	if all == true {
		reqBody, err = json.Marshal(api.AuthRegenerateRequest{All: all})
	} else if username != "" {
		reqBody, err = json.Marshal(api.AuthRegenerateRequest{Name: username})
	}

	if err != nil {
		return "", err
	}

	body, err := c.BasicRequest("POST", "/v1/auth/tokens/", reqBody)

	if err != nil {
		return "", err
	}

	if all == true {
		return "", nil
	}

	token := api.AuthRegenerateResponse{}
	if err = json.Unmarshal([]byte(body), &token); err != nil {
		return "", err
	}

	return token.Token, nil
}
开发者ID:CodeJuan,项目名称:deis,代码行数:32,代码来源:auth.go

示例2: Get

func (i *Incident) Get(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("content-type", "application/json")
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		http.Error(w, "Must append incident id", http.StatusBadRequest)
		return
	}
	index := i.pipeline.GetIndex()

	// if the id is "*", fetch all outstanding incidents
	if id == "*" {
		all := index.ListIncidents()
		all = reduceStatusAbove(event.WARNING, all)
		buff, err := json.Marshal(makeKV(all))
		if err != nil {
			logrus.Error(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Write(buff)
		return
	}

	// write out the found incident. The value will be null if nothing was found
	in := index.GetIncident([]byte(id))
	buff, err := json.Marshal(in)
	if err != nil {
		logrus.Error(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write(buff)
}
开发者ID:postfix,项目名称:bangarang,代码行数:35,代码来源:incident.go

示例3: SendNoLog

func (b *Broker) SendNoLog(resp Response) error {
	b.wLck.Lock()
	defer b.wLck.Unlock()

	if resp.Data == nil {
		resp.Data = M{}
	}

	s, err := json.Marshal(resp)
	if err != nil {
		// if there is a token, it means the client is waiting for a response
		// so respond with the json error. cause of json encode failure includes: non-utf8 string
		if resp.Token == "" {
			return err
		}

		s, err = json.Marshal(M{
			"error": "margo broker: cannot encode json response: " + err.Error(),
		})
		if err != nil {
			return err
		}
	}

	// the only expected write failure are due to broken pipes
	// which usually means the client has gone away so just ignore the error
	b.w.Write(s)
	b.w.Write([]byte{'\n'})
	return nil
}
开发者ID:ntcong,项目名称:sublime-text-2-config,代码行数:30,代码来源:broker.go

示例4: GetTagsListV2Handler

func GetTagsListV2Handler(ctx *macaron.Context, log *logs.BeeLogger) (int, []byte) {
	namespace := ctx.Params(":namespace")
	repository := ctx.Params(":repository")

	r := new(models.Repository)
	if has, _, err := r.Has(namespace, repository); err != nil || has == false {
		log.Error("[REGISTRY API V2] Repository not found: %v", repository)

		result, _ := json.Marshal(map[string]string{"message": "Repository not found"})
		return http.StatusNotFound, result
	}

	data := map[string]interface{}{}
	tags := []string{}

	data["name"] = fmt.Sprintf("%s/%s", namespace, repository)

	for _, value := range r.Tags {
		t := new(models.Tag)
		if err := t.GetByKey(value); err != nil {
			log.Error("[REGISTRY API V2] Tag not found: %v", err.Error())

			result, _ := json.Marshal(map[string]string{"message": "Tag not found"})
			return http.StatusNotFound, result
		}

		tags = append(tags, t.Name)
	}

	data["tags"] = tags

	result, _ := json.Marshal(data)
	return http.StatusOK, result
}
开发者ID:CodeJuan,项目名称:dockyard,代码行数:34,代码来源:manifests.go

示例5: writeSummaries

// writeSummaries retrieves status summaries from the supplied
// NodeStatusRecorder and persists them to the cockroach data store.
func (s *Server) writeSummaries() error {
	nodeStatus, storeStatuses := s.recorder.GetStatusSummaries()
	if nodeStatus != nil {
		key := keys.NodeStatusKey(int32(nodeStatus.Desc.NodeID))
		if err := s.db.Put(key, nodeStatus); err != nil {
			return err
		}
		if log.V(1) {
			statusJSON, err := json.Marshal(nodeStatus)
			if err != nil {
				log.Errorf("error marshaling nodeStatus to json: %s", err)
			}
			log.Infof("node %d status: %s", nodeStatus.Desc.NodeID, statusJSON)
		}
	}

	for _, ss := range storeStatuses {
		key := keys.StoreStatusKey(int32(ss.Desc.StoreID))
		if err := s.db.Put(key, &ss); err != nil {
			return err
		}
		if log.V(1) {
			statusJSON, err := json.Marshal(&ss)
			if err != nil {
				log.Errorf("error marshaling storeStatus to json: %s", err)
			}
			log.Infof("store %d status: %s", ss.Desc.StoreID, statusJSON)
		}
	}
	return nil
}
开发者ID:gechong,项目名称:cockroach,代码行数:33,代码来源:server.go

示例6: Test_LoadConfig_GoodJson

// Tests config file with JSON contents that don't match our structure
func (suite *ConfigTestSuite) Test_LoadConfig_GoodJson() {
	var testObj map[string]interface{}
	var testObjJSON []byte

	// TODO: Test that the config actually gets the values we expect?

	// Has all of our required fields, but no optional fields
	json.Unmarshal(suite.confStubBlob, &testObj)
	for i := range suite.nonRequiredFields {
		delete(testObj, suite.nonRequiredFields[i])
	}
	testObjJSON, _ = json.Marshal(testObj)
	_, err := LoadConfig(testObjJSON)
	suite.Nil(err, "JSON with good values for our required fields but no optional fields should succeed")

	// Has all of our required fields, and all optional fields
	_, err = LoadConfig(suite.confStubBlob)
	suite.Nil(err, "JSON with all good values for required and optional fields should succeed")

	// Has null for optional fields
	json.Unmarshal(suite.confStubBlob, &testObj)
	for i := range suite.nonRequiredFields {
		testObj[suite.nonRequiredFields[i]] = nil
	}
	testObjJSON, _ = json.Marshal(testObj)
	_, err = LoadConfig(testObjJSON)
	suite.Nil(err, "JSON with null for optional values should succeed")
}
开发者ID:Psiphon-Labs,项目名称:psiphon-tunnel-core,代码行数:29,代码来源:config_test.go

示例7: checkstatus

func checkstatus(p *os.Process, pname string, timest string) bool {
	fmt.Println("checkstatus", pname, p)
	reportlog[timest]["status"] = pname + " running"
	reportlog[timest][pname+"start"] = time.Now().Format("20060102150405")
	liner, _ := json.Marshal(reportlog)
	ioutil.WriteFile("static/data/reportlog.json", liner, 0)
	pw, _ := p.Wait()
	fmt.Println("checkstatus over", p)
	fmt.Println("timest=", timest)
	reportlog[timest][pname+"stop"] = time.Now().Format("20060102150405")
	t1, _ := time.Parse("20060102150405", reportlog[timest][pname+"stop"])
	t2, _ := time.Parse("20060102150405", reportlog[timest][pname+"start"])
	reportlog[timest][pname+"time"] = strconv.Itoa(int(t1.Sub(t2)) / 1e9)
	fmt.Println("t1=", t1)
	fmt.Println("t2=", t2)
	fmt.Println("cost=", t1.Sub(t2))
	status := pw.Success()
	if status == true {
		reportlog[timest]["status"] = pname + " success"
		fmt.Println("checkstatus over success ", pname, p)
	} else {
		reportlog[timest]["status"] = pname + " failed"
		fmt.Println("checkstatus over failed ", pname, p)
	}
	liner, _ = json.Marshal(reportlog)
	ioutil.WriteFile("static/data/reportlog.json", liner, 0)
	return status

}
开发者ID:gwenlei,项目名称:linux,代码行数:29,代码来源:build.go

示例8: generateReserveNodeWorkflow

func generateReserveNodeWorkflow(uuid string) ([][]byte, []byte, error) {
	reserve := reserveNodeTask{}
	err := json.Unmarshal(reserveNodeTaskTemplate, &reserve)
	if err != nil {
		return nil, nil, fmt.Errorf("error unmarshalling reserve node task template: %s", err)
	}

	reserve.Name = fmt.Sprintf("%s.%s", reserve.Name, uuid)
	reserve.UnusedName = fmt.Sprintf("%s.%s", reserve.UnusedName, "UPLOADED_BY_RACKHD_CPI")

	reserveBytes, err := json.Marshal(reserve)
	if err != nil {
		return nil, nil, fmt.Errorf("error reserve provision node task template: %s", err)
	}

	w := reserveNodeWorkflow{}
	err = json.Unmarshal(reserveNodeWorkflowTemplate, &w)
	if err != nil {
		return nil, nil, fmt.Errorf("error unmarshalling reserve node workflow template: %s", err)
	}

	w.Name = fmt.Sprintf("%s.%s", w.Name, uuid)
	w.UnusedName = fmt.Sprintf("%s.%s", w.UnusedName, "UPLOADED_BY_RACKHD_CPI")
	w.Tasks[3].TaskName = fmt.Sprintf("%s.%s", w.Tasks[3].TaskName, uuid)

	wBytes, err := json.Marshal(w)
	if err != nil {
		return nil, nil, fmt.Errorf("error marshalling reserve node workflow template: %s", err)
	}

	return [][]byte{reserveBytes}, wBytes, nil
}
开发者ID:cloudfoundry-incubator,项目名称:bosh-rackhd-cpi-release,代码行数:32,代码来源:reserve_node_workflow.go

示例9: MarshalJSON

// Implement json.Marshaler interface.
func (self Week) MarshalJSON() ([]byte, error) {
	if int(self) == Last {
		return json.Marshal(map[string]interface{}{"week": "Last"})
	} else {
		return json.Marshal(map[string]interface{}{"week": int(self)})
	}
}
开发者ID:kenshiro-o,项目名称:recurrence,代码行数:8,代码来源:week.go

示例10: TestIncomingReplication

func TestIncomingReplication(t *testing.T) {
	if testing.Short() {
		t.Skip()
	}

	rep := createMockupReplication()
	close(rep.(*mockupReplication).syncChan) //Make sure no deadlock occur

	ns := auth.NamespaceFrom("ns1")

	r := newInMemoryRegistry(nil, rep)
	assert.NotContains(t, r.(*inMemoryRegistry).namespaces, ns)

	inst := newServiceInstance("Calc1", "192.168.0.1", 9080)
	payload, _ := json.Marshal(inst)
	data, _ := json.Marshal(&replicatedMsg{RepType: REGISTER, Payload: payload})
	rep.(*mockupReplication).NotifyChannel <- &replication.InMessage{cluster.MemberID("192.1.1.3:6100"), ns, data}

	catalog, err := r.GetCatalog(auth.NamespaceFrom("ns1"))

	// NOTICE, it may fail, since a race between the registry and the test...
	time.Sleep(time.Duration(5) * time.Second)

	assert.NoError(t, err)

	instances1, err1 := catalog.List("Calc1", protocolPredicate)
	assert.NoError(t, err1)
	assert.Len(t, instances1, 1)
}
开发者ID:charshy,项目名称:registry,代码行数:29,代码来源:in_memory_registry_test.go

示例11: testJSONEquality

func testJSONEquality(actual, expected interface{}) {
	actualJSON, err := json.Marshal(actual)
	Expect(err).ToNot(HaveOccurred())
	expectedJSON, err := json.Marshal(expected)
	Expect(err).ToNot(HaveOccurred())
	Expect(actualJSON).To(MatchJSON(expectedJSON))
}
开发者ID:gitter-badger,项目名称:gohan,代码行数:7,代码来源:otto_suite_test.go

示例12: generateAncestry

func (ctx *Context) generateAncestry(imageId string, parentId string) error {
	if parentId == "" {
		selfAncestryJson, err := json.Marshal([]string{imageId})
		if err != nil {
			return err
		}
		if err := ctx.storage.PutContent(storage.ImageAncestryPath(imageId), selfAncestryJson); err != nil {
			return err
		}
		return nil
	}

	data, err := ctx.storage.GetContent(storage.ImageAncestryPath(parentId))
	if err != nil {
		return err
	}

	var ancestry []string
	if err := json.Unmarshal(data, &ancestry); err != nil {
		return err
	}

	newAncestry := []string{imageId}
	newAncestry = append(newAncestry, ancestry...)

	data, err = json.Marshal(newAncestry)
	if err != nil {
		return err
	}

	ctx.storage.PutContent(storage.ImageAncestryPath(imageId), data)

	return nil
}
开发者ID:jigish,项目名称:docker-simpleregistry,代码行数:34,代码来源:main.go

示例13: generateAddModule

//database checked
func generateAddModule(id, userId, jwt string, officers, assistants map[string]bool, op *jsonpatch.Operation, params map[string]string) (*jsonpatch.CommandContainer, error) {
	if err := checkAuthorityAndValidatePatch(jsonpatch.ADD, op.Type, userId, officers); err != nil {
		log.Println("Patch not acceptable: ", err)
		return nil, err
	}
	value := op.Value.(map[string]interface{})
	command := buildDefaultCommand("SELECT add_module(%v)", value["id"].(string), id, value["description"].(string), value["video_id"].(string), value["script_id"].(string), value["parents"])
	command.AfterCallback = func(transaction, prev interface{}) (interface{}, error) {
		client := serviceclient.New("acl-service")
		entity := map[string]interface{}{
			"id":     value["id"].(string),
			"parent": id,
		}
		jsonEntity, _ := json.Marshal(entity)
		err := checkStatus(client.Post("/objects", "json", bytes.NewReader(jsonEntity), "Authorization", jwt))
		if err != nil {
			log.Println("error while creating acl entry: ", err)
			return nil, err
		}
		if len(assistants) > 0 {
			assistantsString := ""
			for k, _ := range assistants {
				assistantsString = assistantsString + "&sid=" + k
			}
			assistantsString = strings.TrimLeft(assistantsString, "&")
			permissions, _ := json.Marshal(map[string]bool{"read_permission": true, "create_permission": true, "update_permission": false, "delete_permission": false})
			return nil, checkStatus(client.Put(fmt.Sprintf("/objects/%s/permissions?%s", value["id"], assistantsString), "application/json", bytes.NewReader(permissions), "Authorization", jwt))
		}
		return nil, nil
	}
	return command, nil
}
开发者ID:InteractiveLecture,项目名称:lecture-service,代码行数:33,代码来源:topicpatchcompiler.go

示例14: TestGetTimestampNewSnapshot

func TestGetTimestampNewSnapshot(t *testing.T) {
	store := storage.NewMemStorage()
	crypto := signed.NewEd25519()

	snapshot := &data.SignedSnapshot{
		Signed: data.Snapshot{
			Expires: data.DefaultExpires(data.CanonicalSnapshotRole),
		},
	}
	snapshot.Signed.Version = 0
	snapJSON, _ := json.Marshal(snapshot)

	store.UpdateCurrent("gun", storage.MetaUpdate{Role: "snapshot", Version: 0, Data: snapJSON})
	// create a key to be used by GetTimestamp
	_, err := GetOrCreateTimestampKey("gun", store, crypto, data.ED25519Key)
	assert.Nil(t, err, "GetKey errored")

	ts1, err := GetOrCreateTimestamp("gun", store, crypto)
	assert.Nil(t, err, "GetTimestamp errored")

	snapshot = &data.SignedSnapshot{
		Signed: data.Snapshot{
			Expires: data.DefaultExpires(data.CanonicalSnapshotRole),
		},
	}
	snapshot.Signed.Version = 1
	snapJSON, _ = json.Marshal(snapshot)

	store.UpdateCurrent("gun", storage.MetaUpdate{Role: "snapshot", Version: 1, Data: snapJSON})

	ts2, err := GetOrCreateTimestamp("gun", store, crypto)
	assert.NoError(t, err, "GetTimestamp errored")

	assert.NotEqual(t, ts1, ts2, "Timestamp was not regenerated when snapshot changed")
}
开发者ID:moxiegirl,项目名称:notary,代码行数:35,代码来源:timestamp_test.go

示例15: MarshalJSON

// MarshalJSON returns either the slug or id of the image. It returns the id
// if the slug is empty.
func (d DropletCreateImage) MarshalJSON() ([]byte, error) {
	if d.Slug != "" {
		return json.Marshal(d.Slug)
	}

	return json.Marshal(d.ID)
}
开发者ID:Originate,项目名称:terraform,代码行数:9,代码来源:droplets.go


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