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


Golang json.MarshalIndent函数代码示例

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


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

示例1: runQueryExtended

func runQueryExtended(engine EngineI, query string, c *C, appendPoints bool, expectedSeries string) {

	var result []*protocol.Series
	err := engine.RunQuery(nil, "", query, func(series *protocol.Series) error {
		if appendPoints && result != nil {
			result[0].Points = append(result[0].Points, series.Points...)
		} else {
			result = append(result, series)
		}
		return nil
	})

	c.Assert(err, IsNil)

	series, err := common.StringToSeriesArray(expectedSeries)
	c.Assert(err, IsNil)

	if !reflect.DeepEqual(result, series) {
		resultData, _ := json.MarshalIndent(result, "", "  ")
		seriesData, _ := json.MarshalIndent(series, "", "  ")

		fmt.Fprintf(os.Stderr,
			"===============\nThe two series aren't equal.\nExpected: %s\nActual: %s\n===============\n",
			seriesData, resultData)
	}

	c.Assert(result, DeepEquals, series)
}
开发者ID:rudrapranay,项目名称:influxdb,代码行数:28,代码来源:engine_test.go

示例2: GetOS

func GetOS(w http.ResponseWriter, r *http.Request) {
	var os_query libocit.OS
	os_query = GetOSQuery(r)

	ids := GetResourceList(os_query)

	var ret libocit.HttpRet
	if len(ids) < 1 {
		ret.Status = "Failed"
		ret.Message = "Cannot find the avaliable OS"
	} else {
		ret.Status = "OK"
		ret.Message = "Find the avaliable OS"
		var oss []libocit.OS
		for index := 0; index < len(ids); index++ {
			oss = append(oss, *(store[ids[index]]))
		}

		data, _ := json.MarshalIndent(oss, "", "\t")
		ret.Data = string(data)
	}

	body, _ := json.MarshalIndent(ret, "", "\t")
	w.Write([]byte(body))
}
开发者ID:sdgdsffdsfff,项目名称:oct-engine,代码行数:25,代码来源:testserver.go

示例3: ServeHTTP

// ServeHTTP shows the current plans in the query cache.
func (plr *Planner) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	if err := acl.CheckAccessHTTP(request, acl.DEBUGGING); err != nil {
		acl.SendError(response, err)
		return
	}
	if request.URL.Path == "/debug/query_plans" {
		keys := plr.plans.Keys()
		response.Header().Set("Content-Type", "text/plain")
		response.Write([]byte(fmt.Sprintf("Length: %d\n", len(keys))))
		for _, v := range keys {
			response.Write([]byte(fmt.Sprintf("%#v\n", v)))
			if plan, ok := plr.plans.Peek(v); ok {
				if b, err := json.MarshalIndent(plan, "", "  "); err != nil {
					response.Write([]byte(err.Error()))
				} else {
					response.Write(b)
				}
				response.Write(([]byte)("\n\n"))
			}
		}
	} else if request.URL.Path == "/debug/vschema" {
		response.Header().Set("Content-Type", "application/json; charset=utf-8")
		b, err := json.MarshalIndent(plr.VSchema().Keyspaces, "", " ")
		if err != nil {
			response.Write([]byte(err.Error()))
			return
		}
		buf := bytes.NewBuffer(nil)
		json.HTMLEscape(buf, b)
		response.Write(buf.Bytes())
	} else {
		response.WriteHeader(http.StatusNotFound)
	}
}
开发者ID:dumbunny,项目名称:vitess,代码行数:35,代码来源:planner.go

示例4: SaveConfig

// Saves either of the two config types to the specified file with the specified permissions.
func SaveConfig(fileout string, config interface{}, perms os.FileMode) error {

	//check to see if we got a struct or a map (minimal or extended config, respectively)
	v := reflect.ValueOf(config)
	if v.Kind() == reflect.Struct {
		config := config.(Config)

		//Parse the nicely formatted security section, and set the raw values for JSON marshalling
		newSecurity := make([]interface{}, 0)
		if config.Security.NoFiles {
			newSecurity = append(newSecurity, "nofiles")
		}
		setuser := make(map[string]interface{})
		setuser["setuser"] = config.Security.SetUser
		newSecurity = append(newSecurity, setuser)
		config.RawSecurity = newSecurity

		jsonout, err := json.MarshalIndent(config, "", "    ")
		if err != nil {
			return err
		}
		return ioutil.WriteFile(fileout, jsonout, perms)
	} else if v.Kind() == reflect.Map {
		jsonout, err := json.MarshalIndent(config, "", "    ")
		if err != nil {
			return err
		}
		return ioutil.WriteFile(fileout, jsonout, perms)
	}
	return fmt.Errorf("Something very bad happened")
}
开发者ID:waaghals,项目名称:go-cjdns,代码行数:32,代码来源:config.go

示例5: TestUnmarshal

func TestUnmarshal(t *testing.T) {
	tests := []struct {
		filename string
		typ      interface{}
		expected string
	}{
		// ASCII
		{"ascii.mof", MSFT_DSCConfigurationStatus{}, asciiMOFExpected},

		// UTF-16, little-endian
		{"utf16-le.mof", MSFT_DSCConfigurationStatus{}, utf16leMOFExpected},
	}
	for _, test := range tests {
		b, err := ioutil.ReadFile(test.filename)
		if err != nil {
			t.Fatal(err)
		}
		var v interface{}
		if err := Unmarshal(b, &v); err != nil {
			t.Fatal(err)
		}
		s := test.typ
		if err := Unmarshal(b, &s); err != nil {
			t.Fatal(err)
		}
		vb, _ := json.MarshalIndent(&v, "", "  ")
		sb, _ := json.MarshalIndent(&s, "", "  ")
		if string(vb) != test.expected {
			t.Errorf("%v: unexpected interface value", test.filename)
		}
		if string(sb) != test.expected {
			t.Errorf("%v: unexpected struct value", test.filename)
		}
	}
}
开发者ID:eswdd,项目名称:bosun,代码行数:35,代码来源:mof_test.go

示例6: equal

func equal(got, want string) error {
	var v1, v2 interface{}

	if err := json.Unmarshal([]byte(got), &v1); err != nil {
		return err
	}

	if err := json.Unmarshal([]byte(want), &v2); err != nil {
		return err
	}

	stripNondeterministicResources(v1)
	stripNondeterministicResources(v2)

	if !reflect.DeepEqual(v1, v2) {
		p1, err := json.MarshalIndent(v1, "", "\t")
		if err != nil {
			panic(err)
		}

		p2, err := json.MarshalIndent(v2, "", "\t")
		if err != nil {
			panic(err)
		}

		return fmt.Errorf("got:\n%s\nwant:\n%s\n", p1, p2)
	}

	return nil
}
开发者ID:koding,项目名称:koding,代码行数:30,代码来源:stack_test.go

示例7: pubTxnCollectionIfNotExist

func (o TxnManager) pubTxnCollectionIfNotExist(txnId int, collection string) {
	query := map[string]interface{}{
		"_id": txnId,
		"collections": map[string]interface{}{
			"$nin": []string{collection},
		},
	}
	update := map[string]interface{}{
		"$push": map[string]interface{}{
			"collections": collection,
		},
	}
	updateByte, err := json.MarshalIndent(&update, "", "\t")
	if err != nil {
		panic(err)
	}
	queryByte, err := json.MarshalIndent(&query, "", "\t")
	if err != nil {
		panic(err)
	}
	log.Println("pubTxnCollectionIfNotExist,update Transactions update:" + string(updateByte) + ", query:" + string(queryByte))
	if err := o.DB.C("Transactions").Update(query, update); err != nil {
		if err != mgo.ErrNotFound {
			panic(err)
		}
	}
}
开发者ID:hongjinqiu,项目名称:finance,代码行数:27,代码来源:TxnManager.go

示例8: TestInterfaceSchema

func TestInterfaceSchema(t *testing.T) {
	var config struct {
		Field interface{}
	}

	schema := Of(config)
	value, _ := json.MarshalIndent(schema, "", "    ")
	t.Log(string(value))

	value, _ = json.MarshalIndent(schema, "\t\t", "    ")
	assert.Equal(t, string(value), `{
		    "schema": {
		        "type": "object",
		        "properties": {
		            "Field": {
		                "type": "string",
		                "required": true,
		                "title": "Field",
		                "propertyOrder": 1
		            }
		        },
		        "required": true,
		        "title": ""
		    }
		}`)
}
开发者ID:choirudin2210,项目名称:platform-layer,代码行数:26,代码来源:schema_test.go

示例9: ExampleMessage

func ExampleMessage() {
	client := wit.NewClient(os.Getenv("WIT_ACCESS_TOKEN"))

	// Process a text message
	request := &wit.MessageRequest{}
	request.Query = "Hello world"
	result, err := client.Message(request)
	if err != nil {
		log.Println(err)
		os.Exit(-1)
	}
	log.Println(result)
	data, _ := json.MarshalIndent(result, "", "    ")
	log.Println(string(data[:]))

	// Process an audio/wav message
	request = &wit.MessageRequest{}
	request.File = "../audio_sample/helloWorld.wav"
	request.ContentType = "audio/wav;rate=8000"
	result, err = client.AudioMessage(request)
	if err != nil {
		log.Println(err)
		os.Exit(-1)
	}
	log.Println(result)
	data, _ = json.MarshalIndent(result, "", "    ")
	log.Println(string(data[:]))
}
开发者ID:Ripleather,项目名称:starter-go-bot,代码行数:28,代码来源:message.go

示例10: TestCmdInspectFormat

func TestCmdInspectFormat(t *testing.T) {
	actual, host := runInspectCommand(t, []string{"test-a"})
	expected, _ := json.MarshalIndent(host, "", "    ")
	assert.Equal(t, string(expected), actual)

	actual, _ = runInspectCommand(t, []string{"--format", "{{.DriverName}}", "test-a"})
	assert.Equal(t, "none", actual)

	actual, _ = runInspectCommand(t, []string{"--format", "{{json .DriverName}}", "test-a"})
	assert.Equal(t, "\"none\"", actual)

	actual, _ = runInspectCommand(t, []string{"--format", "{{prettyjson .Driver}}", "test-a"})
	type ExpectedDriver struct {
		CaCertPath     string
		IPAddress      string
		MachineName    string
		PrivateKeyPath string
		SSHPort        int
		SSHUser        string
		SwarmDiscovery string
		SwarmHost      string
		SwarmMaster    bool
		URL            string
	}
	expected, err := json.MarshalIndent(&ExpectedDriver{MachineName: "test-a", URL: "unix:///var/run/docker.sock"}, "", "    ")
	assert.NoError(t, err)
	assert.Equal(t, string(expected), actual)
}
开发者ID:phusl,项目名称:machine,代码行数:28,代码来源:inspect_test.go

示例11: processRefreshTokenFlow

func processRefreshTokenFlow(authRequest mongodb.Document) (responseContent []byte) {

	var err error
	var user mongodb.Document
	var token mongodb.Document
	var accessToken mongodb.Document
	var refreshToken mongodb.Document

	token, err = getToken(authRequest[REFRESH_TOKEN].(string), authRequest[CLIENT_ID].(string), REFRESH_TOKEN_COLLECTION)

	if err == nil {
		//check if user exists
		user, err = getUser(mongodb.Document{ID: token[USER_ID]}) //get user from db
		if err == nil {
			//create tokens
			accessToken, err = generateToken(user, authRequest, ACCESS_TOKEN_COLLECTION)
			if err == nil {
				refreshToken, err = generateToken(user, authRequest, REFRESH_TOKEN_COLLECTION)
			}
		}
	}

	if err != nil {
		mwError := bson.M{"errorCode": "500", "errorMessage": err.Error()}
		responseContent, _ = json.MarshalIndent(mwError, "", "  ")
	} else {
		//success reponse with toekn info.
		tokenInfo := bson.M{ACCESS_TOKEN: accessToken[TOKEN], REFRESH_TOKEN: refreshToken[TOKEN]}
		responseContent, _ = json.MarshalIndent(tokenInfo, "", "  ")
	}

	return responseContent
}
开发者ID:hkolasani,项目名称:goauth,代码行数:33,代码来源:mongoweb.go

示例12: TestLex

func TestLex(t *testing.T) {
	for _, test := range lexTests {
		for i, _ := range test.ast.Classes {
			test.ast.Classes[i].Filename = "test.manifest"
			normalizeBlock(&test.ast.Classes[i].Block, "test.manifest")
		}
		for i, _ := range test.ast.Defines {
			test.ast.Defines[i].Filename = "test.manifest"
			normalizeBlock(&test.ast.Defines[i].Block, "test.manifest")
		}
		for i, _ := range test.ast.Nodes {
			test.ast.Nodes[i].Filename = "test.manifest"
			normalizeBlock(&test.ast.Nodes[i].Block, "test.manifest")
		}

		ast := NewAST()
		if err := Parse(ast, "test.manifest", strings.NewReader(test.manifest)); err != nil {
			t.Log(test.manifest)
			t.Error(err)
		} else {
			if !equalsAsJson(ast, test.ast) {
				t.Logf("%#v", test.ast)
				t.Logf("%#v", ast)
				js2, _ := json.MarshalIndent(test.ast, "", "  ")
				t.Log(string(js2))
				js, _ := json.MarshalIndent(ast, "", "  ")
				t.Log(string(js))
				t.Error("Expected manifest", test.manifest)
				if ast != nil {
					t.Log("Read manifest", ast.String())
				}
			}
		}
	}
}
开发者ID:yoshiyaka,项目名称:mosa,代码行数:35,代码来源:lex_test.go

示例13: logFiles

func (s *Site) logFiles() {
	log := make([]Event, len(s.L))
	i := 0
	for k := range s.L {
		log[i] = k
		i++
	}
	slog, err := json.MarshalIndent(log, "", "\t")
	if err != nil {
		fmt.Printf("%+v\n", err)
	} else {
		ioutil.WriteFile("log.json", slog, 0666)
	}

	cal := make([]Appointment, len(s.V))
	i = 0
	for _, v := range s.V {
		cal[i] = v
		i++
	}
	scal, err := json.MarshalIndent(cal, "", "\t")
	if err != nil {
		fmt.Printf("%+v\n", err)
	} else {
		ioutil.WriteFile("cal.json", scal, 0666)
	}
}
开发者ID:CannedYerins,项目名称:distributed-systems,代码行数:27,代码来源:site.go

示例14: ToJSON

// ToJSON returns a JSON representation of the object.
func (n *ActionNode) ToJSON() (string, error) {
	data, err := json.MarshalIndent(n, "", "  ")
	if err != nil {
		return "", fmt.Errorf("cannot JSON-marshal node: %v", err)
	}
	result := string(data) + "\n"
	if n.Args == nil {
		result += "{}\n"
	} else {
		data, err := json.MarshalIndent(n.Args, "", "  ")
		if err != nil {
			return "", fmt.Errorf("cannot JSON-marshal node args: %v", err)
		}
		result += string(data) + "\n"
	}
	if n.Reply == nil {
		result += "{}\n"
	} else {
		data, err := json.MarshalIndent(n.Reply, "", "  ")
		if err != nil {
			return "", fmt.Errorf("cannot JSON-marshal node reply: %v", err)
		}
		result += string(data) + "\n"
	}
	return result, nil
}
开发者ID:aaijazi,项目名称:vitess,代码行数:27,代码来源:actionnode.go

示例15: testFlatten

func testFlatten(inputFile, outputFile, contextFile, base string,
	compactArrays bool, t *testing.T) {
	inputJson, jsonErr := ReadJSONFromFile(test_dir + inputFile)
	if !isNil(jsonErr) {
		t.Error("Could not open input file")
		return
	}
	outputJson, jsonErr := ReadJSONFromFile(test_dir + outputFile)
	if !isNil(jsonErr) {
		t.Error("Could not open output file")
		return
	}
	contextJson, jsonErr := ReadJSONFromFile(test_dir + contextFile)
	if !isNil(jsonErr) {
		contextJson = nil
	}
	options := &Options{
		Base:           base,
		CompactArrays:  compactArrays,
		ExpandContext:  nil,
		DocumentLoader: NewDocumentLoader(),
	}
	flattenedJson, flattenErr := Flatten(inputJson, contextJson, options)
	if !isNil(flattenErr) {
		t.Error("Compaction failed with error ", flattenErr.Error())
		return
	}
	flattenedString, _ := json.MarshalIndent(flattenedJson, "", "    ")
	outputString, _ := json.MarshalIndent(outputJson, "", "    ")
	if !reflect.DeepEqual(flattenedJson, outputJson) {
		t.Error("Expected:\n", string(outputString), "\nGot:\n",
			string(flattenedString))
	}
}
开发者ID:peacekeeper,项目名称:golang-github-linkeddata-gojsonld-dev,代码行数:34,代码来源:flatten_test.go


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