Home > Backend Development > Golang > JSON array as Go structure

JSON array as Go structure

王林
Release: 2024-02-10 18:00:20
forward
921 people have browsed it

JSON 数组作为 Go 结构

php Xiaobian Yuzai introduces you to the use of JSON arrays as Go structures. In Go language, JSON array is a common data structure, which can be used to represent multiple data of the same type. By mapping JSON arrays to Go structures, we can easily operate and process them. This article will introduce in detail how to use the JSON package in the Go language to parse and build JSON arrays, and convert them into corresponding Go structures to achieve effective management and processing of data. Whether you are a beginner in Go or an experienced developer, this article will bring you practical tips and methods to help you better understand and apply JSON arrays as Go structures.

Question content

I'm trying to call an array of objects from a json file but always get the error: "Cannot unmarshal array into go value of type config.appconfig". How do I make sure my go structure calls an array of objects in a json file? The following are the configuration files and json files I used to set up the go structure:

config.go

package config

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

type easy struct {
 uid string `json:"uid"`
}

type auth struct {
 code string `json:"code"`
}

type appconfig struct {
 openapimode string `json:"openapimode"` 
 openapiurl  string `json:"openapiurl"`  

 clientid string `json:"clientid"` 
 secret   string `json:"secret"` 

 authmode string `json:"authmode"`

 easy easy `json:"easy"`
 auth auth `json:"auth"`

 deviceid string `json:"deviceid"`

 uid          string `json:"-"` 
 mqttuid      string `json:"-"` 
 accesstoken  string `json:"-"`
 refreshtoken string `json:"-"`
 expiretime   int64  `json:"-"`
}

var app = appconfig{
  openapimode: "mqtt",
  openapiurl:  "openapi.tuyacn.com",
}


func loadconfig() error {
  return parsejson("webrtc.json", &app)
}

func parsejson(path string, v interface{}) error {
  data, err := ioutil.readfile(path)
  if err != nil {
    return err
}

 err = json.unmarshal(data, v)
 return err
}
Copy after login

json file

[
  {
    "openAPIMode": "mqtt",
    "openAPIUrl": "openapi.tuyaus.com",
    "clientId": "*****",
    "secret": "**************",
    "authMode": "easy",
    "easy": {
      "uId": "**********"
    },
    "auth": {
      "code": ""
    },
    "deviceId": "***********"
  },
  {
    "openAPIMode": "mqtt",
    "openAPIUrl": "openapi.tuyaus.com",
    "clientId": "*****",
    "secret": "**************",
    "authMode": "easy",
    "easy": {
      "uId": "**********"
    },
    "auth": {
      "code": ""
    },
    "deviceId": "***********"
  }
]
Copy after login

Thanks in advance for your help!

Workaround

Your configuration json file is a json array and you are parsing it into a structure, you need to parse it into an array of structures.

To fix your code, change the initialization of app to this.

var app []appconfig

func loadconfig() error {
    return parsejson("webrtc.json", &app)
}
Copy after login

This is the complete sample code.

package main

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

type Easy struct {
    UID string `json:"uId"`
}

type Auth struct {
    Code string `json:"code"`
}

type APPConfig struct {
    OpenAPIMode string `json:"openAPIMode"`
    OpenAPIURL  string `json:"openAPIUrl"`

    ClientID string `json:"clientId"`
    Secret   string `json:"secret"`

    AuthMode string `json:"authMode"`

    Easy Easy `json:"easy"`
    Auth Auth `json:"auth"`

    DeviceID string `json:"deviceId"`

    UID          string `json:"-"`
    MQTTUID      string `json:"-"`
    AccessToken  string `json:"-"`
    RefreshToken string `json:"-"`
    ExpireTime   int64  `json:"-"`
}

var App []APPConfig

func LoadConfig() error {
    return parseJSON("webrtc.json", &App)
}

func parseJSON(path string, v interface{}) error {
    data, err := ioutil.ReadFile(path)
    if err != nil {
        return err
    }

    err = json.Unmarshal(data, v)
    return err
}

func main() {
    err := LoadConfig()
    if err != nil {
        panic(err)
    }
    fmt.Printf("%+v\n", App)
}
Copy after login

The above is the detailed content of JSON array as Go structure. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:stackoverflow.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template