Tuesday 14 May 2024

GO LANG example of reading a file and format to json

 package main


import (

"bufio"

"encoding/json"

"fmt"

"os"

"strings"

)


func main() {

// Open the file

file, err := os.Open("data.txt")

if err != nil {

fmt.Println("Error opening file:", err)

return

}

defer file.Close()


// Initialize a map to store key-value pairs

data := make(map[string]string)


// Read the file line by line

scanner := bufio.NewScanner(file)

for scanner.Scan() {

line := scanner.Text()

// Split each line into key and value

parts := strings.Split(line, ":")

if len(parts) == 2 {

key := strings.TrimSpace(parts[0])

value := strings.TrimSpace(parts[1])

// Add key-value pair to the map

data[key] = value

}

}


if err := scanner.Err(); err != nil {

fmt.Println("Error reading file:", err)

return

}


// Format the map as JSON

jsonData, err := json.Marshal(data)

if err != nil {

fmt.Println("Error encoding JSON:", err)

return

}


// Print the JSON response

fmt.Println(string(jsonData))

}

No comments:

Post a Comment