Home > Blockchain >  read arrays from a JSON file to your GO variables
read arrays from a JSON file to your GO variables

Time:11-01

I have been tasked with converting my project from Python to Go, but I've been stumped for hours on this.

I have this file data.json which contains the following data

{
    "mobiles":["iPhone 13 Pro","OnePlus 10 Pro","Google Pixel 6"], 
    "laptops":["Dell XSP 13","Acer Chromebook Spin","Lenovo ThinkPad x1"], 
    "cars":["Suzuki Crossover","Golf GTI","Hyundai Tucson","Hyundai Kona"]
}

For my project, I would like to load the data from data.json into the following slices

mobiles := []{ data from json }
laptops := []{ data from json }
cars := []{ data from json }

I'm thinking of using slices, if I'm not wrong would that allow me to add more data to my arrays in the json file as I need?

    jsonFile, err := os.Open("data/data.json")  
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(jsonFile)
    fmt.Println("Successfully Opened data.json")

This gives me: &{0xc000062180} Successfully Opened data.json

I was trying to target the data I need with for example:

fmt.Println(jsonFile["cars"])

Do I need to learn about pointers or am I completly barking up the wrong tree?

CodePudding user response:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "os"
)

type Todo struct {
    Mobiles []string `json:"mobiles"`
    Laptops  []string `json:"laptops"`
    Cars  []string `json:"cars"`
}

func main() {
    jsonFile, err := os.Open("file.json")
    if err != nil {
        panic(err)
    }
    
    defer jsonFile.Close()

    byteValue, err := ioutil.ReadAll(jsonFile)
    if err != nil {
        panic(err)
    }

    var todo Todo
    json.Unmarshal([]byte(byteValue), &todo)

    fmt.Println(todo)
    fmt.Println(todo.Cars)
}

the first output will be your json file

{[iPhone 13 Pro OnePlus 10 Pro Google Pixel 6] [Dell XSP 13 Acer Chromebook Spin Lenovo ThinkPad x1] [Suzuki Crossover Golf GTI Hyundai Tucson Hyundai Kona]}

and the second the cars

[Suzuki Crossover Golf GTI Hyundai Tucson Hyundai Kona]

  • Related