search
HomeBackend DevelopmentGolangUse the json.MarshalIndent function in golang to convert the structure into a formatted JSON string

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string

When writing programs using Golang, we often need to convert the structure into Convert to JSON string. In this process, the json.MarshalIndent function can help us achieve formatted output. Below we will explain in detail how to use this function and provide specific code examples.

First, let's create a structure containing some data. The following is the sample code:

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

func main() {
    person := Person{
        Name:  "John",
        Age:   30,
        Email: "john@example.com",
    }

    // 将Person结构体转换为JSON字符串
    jsonData, err := json.MarshalIndent(person, "", "  ")
    if err != nil {
        fmt.Println("转换为JSON字符串时发生错误:", err)
        return
    }

    // 打印格式化的JSON字符串
    fmt.Println(string(jsonData))
}

In the above code, we first define a Person structure containing name, age and email. Then create a Person object in the main function and convert the object to a JSON string using the json.MarshalIndent function.

When calling the json.MarshalIndent function, the function requires three parameters. The first parameter is the object to be converted, the second parameter is the prefix at the beginning of the line, and the third parameter is each indent. Level interval. In the example code, we set the second parameter to an empty string and the third parameter to two spaces. In this way, you can get a JSON string indented according to the specified format.

Finally, we use the fmt.Println function to print the formatted JSON string.

Run the above code and you will get the following output:

{
  "name": "John",
  "age": 30,
  "email": "john@example.com"
}

As we can see, it is very simple to use the json.MarshalIndent function to convert the structure into a formatted JSON string. We only need to specify some parameters to get a JSON string indented according to the specified format.

Summary:
In this article, we introduced how to use the json.MarshalIndent function in golang to convert a structure into a formatted JSON string. By giving suitable parameters, we can easily get the output in JSON format that meets the requirements. Whether it is converting a structure into a JSON string or parsing it from a JSON string into a structure, the encoding/json package in Golang's standard library provides many useful functions to facilitate JSON encoding and decoding operations.

The above is the detailed content of Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Using init for Package Initialization in GoUsing init for Package Initialization in GoApr 24, 2025 pm 06:25 PM

In Go, the init function is used for package initialization. 1) The init function is automatically called when package initialization, and is suitable for initializing global variables, setting connections and loading configuration files. 2) There can be multiple init functions that can be executed in file order. 3) When using it, the execution order, test difficulty and performance impact should be considered. 4) It is recommended to reduce side effects, use dependency injection and delay initialization to optimize the use of init functions.

Go's Select Statement: Multiplexing Concurrent OperationsGo's Select Statement: Multiplexing Concurrent OperationsApr 24, 2025 pm 05:21 PM

Go'sselectstatementstreamlinesconcurrentprogrammingbymultiplexingoperations.1)Itallowswaitingonmultiplechanneloperations,executingthefirstreadyone.2)Thedefaultcasepreventsdeadlocksbyallowingtheprogramtoproceedifnooperationisready.3)Itcanbeusedforsend

Advanced Concurrency Techniques in Go: Context and WaitGroupsAdvanced Concurrency Techniques in Go: Context and WaitGroupsApr 24, 2025 pm 05:09 PM

ContextandWaitGroupsarecrucialinGoformanaginggoroutineseffectively.1)ContextallowssignalingcancellationanddeadlinesacrossAPIboundaries,ensuringgoroutinescanbestoppedgracefully.2)WaitGroupssynchronizegoroutines,ensuringallcompletebeforeproceeding,prev

The Benefits of Using Go for Microservices ArchitectureThe Benefits of Using Go for Microservices ArchitectureApr 24, 2025 pm 04:29 PM

Goisbeneficialformicroservicesduetoitssimplicity,efficiency,androbustconcurrencysupport.1)Go'sdesignemphasizessimplicityandefficiency,idealformicroservices.2)Itsconcurrencymodelusinggoroutinesandchannelsallowseasyhandlingofhighconcurrency.3)Fastcompi

Golang vs. Python: The Pros and ConsGolang vs. Python: The Pros and ConsApr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang and C  : Concurrency vs. Raw SpeedGolang and C : Concurrency vs. Raw SpeedApr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Why Use Golang? Benefits and Advantages ExplainedWhy Use Golang? Benefits and Advantages ExplainedApr 21, 2025 am 12:15 AM

Reasons for choosing Golang include: 1) high concurrency performance, 2) static type system, 3) garbage collection mechanism, 4) rich standard libraries and ecosystems, which make it an ideal choice for developing efficient and reliable software.

Golang vs. C  : Performance and Speed ComparisonGolang vs. C : Performance and Speed ComparisonApr 21, 2025 am 12:13 AM

Golang is suitable for rapid development and concurrent scenarios, and C is suitable for scenarios where extreme performance and low-level control are required. 1) Golang improves performance through garbage collection and concurrency mechanisms, and is suitable for high-concurrency Web service development. 2) C achieves the ultimate performance through manual memory management and compiler optimization, and is suitable for embedded system development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.