Current code:
package main
import (
"bufio"
"encoding/json"
"fmt"
"log"
"os"
)
/*
Prompt: Parse JSON
Task: Write a program that reads a JSON string representing a list
of people (with fields for name and age) and parses it into a slice of structs.
Then, print out the names and ages of all people in the list.
STATUS: PENDING
*/
func check(err error) error {
if err != nil {
// Throw error if the file is NULL
log.Fatal(err)
}
return err
}
func main() {
fmt.Println("This is a JSON parser")
// Read entire file at once
content, err := os.ReadFile("read.json")
check(err)
// Print content
fmt.Println(string(content))
// Go over the document word by word
file, err2 := os.Open("read.json")
check(err2)
scan := bufio.NewScanner(file)
scan.Split(bufio.ScanWords)
// Parse JSON into a struct
// JSON decoder
parser := json.NewDecoder(file)
var person people
err = parser.Decode(&person)
if err != nil {
// WARNING
log.Fatalf("Failed to decode JSON: %s", err)
}
// reflect --> It enables you to examine the type and value of variables dynamically.
fmt.Printf("Name: %s\n", person.name)
fmt.Printf("Age: %d\n", person.age)
fmt.Printf("City: %s\n", person.city)
file.Close()
}
// Struct declaration
type people struct {
name string
age uint8
city string
}
Hi, so I'm trying to use this fairly easy JSON parser, that I don't really fully understand myself even though I wrote it, to take a small JSON file, show it on screen and then print its values in a nicer way, I got to print it but the end result is like this:
This is a JSON parser
{
"name": "Alice",
"age": 30,
"city": "New York"
}
Name:
Age: 0
City:
How can I fix this? anything I might be missing? If there is any tutorial that explains how to do this task properly, please let me know