Golang
Golang

 

 

Introduction

JSON (JavaScript Object Notation) is a popular format for data exchange due to its simplicity and readability. However, raw JSON can often be compact and hard to interpret. Formatting a JSON string to make it more readable is a common requirement for developers during debugging or data analysis. This program demonstrates how to use Go (Golang) to format a JSON string into a more human-readable structure with proper indentation.

Objective

The goal of this program is to take a compact JSON string as input, format it with indentation for better readability, and output the formatted JSON string. This program is intended for beginners and intermediate developers looking to understand JSON parsing and formatting in Go.

Code

        package main

        import (
            "bytes"
            "encoding/json"
            "fmt"
            "os"
        )

        func main() {
            // Example compact JSON string
            compactJSON := `{"name":"John","age":30,"city":"New York","languages":["English","Spanish"]}`

            // Call the formatJSON function
            formattedJSON, err := formatJSON(compactJSON)
            if err != nil {
                fmt.Fprintf(os.Stderr, "Error formatting JSON: %v\n", err)
                os.Exit(1)
            }

            // Print the formatted JSON
            fmt.Println("Formatted JSON:")
            fmt.Println(formattedJSON)
        }

        // formatJSON takes a compact JSON string and returns a formatted version with indentation
        func formatJSON(input string) (string, error) {
            var buffer bytes.Buffer

            // Unmarshal the JSON into a generic interface
            var rawJSON interface{}
            err := json.Unmarshal([]byte(input), &rawJSON)
            if err != nil {
                return "", err
            }

            // Marshal the JSON with indentation into the buffer
            err = json.NewEncoder(&buffer).Encode(rawJSON)
            if err != nil {
                return "", err
            }

            return buffer.String(), nil
        }

Explanation

This program performs the following steps:

  1. Import necessary packages: The program uses the encoding/json package for JSON operations and bytes for buffering the output.
  2. Define a sample JSON string: A compact JSON string is used as an example input.
  3. Unmarshal the JSON: The compact JSON string is unmarshaled into a generic interface, allowing Go to understand its structure.
  4. Marshal with indentation: The unmarshaled JSON is then marshaled back into a formatted JSON string with indentation using a buffer.
  5. Handle errors: Errors during unmarshaling or marshaling are captured and displayed.

How to Run

  1. Install Go from the official Go website.
  2. Copy the code into a file named format_json.go.
  3. Run the program using the command:
                    go run format_json.go
    
  4. Observe the formatted JSON output in the terminal.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)