Here is my code:
package main
import "fmt"
type Species struct {
Human []Info
Animal []Info
}
type Info struct {
Name string
Number string
}
func main() {
var data Species
data = ????
fmt.Println(data)
}
I want to see it as json like this:
{
"human":[
{"name":"dave","number":"00001"},
{"name":"jack","number":"00002"},
{"name":"nate","number":"00003"}
],
"animal":[
{"name":"ko","number":"00004"},
{"name":"na","number":"00005"}
]
}
I don't know how to put in data that struct. What do I write on '???' in code?
form json pkg you can encoding and decoding JSON format
package main
import (
"encoding/json"
"fmt"
)
type Species struct {
Human []Info `json:"human"`
Animal []Info `json:"animal"`
}
type Info struct {
Name string `json:"name"`
Number string `json:"number"`
}
func main() {
data := Species{
Human: []Info{
Info{Name: "dave", Number: "00001"},
Info{Name: "jack", Number: "00002"},
},
Animal: []Info{
Info{Name: "ko", Number: "00004"},
Info{Name: "na", Number: "00005"},
},
}
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(string(b))
}
https://play.golang.org/p/evQto70Z8y
Related
I am trying to call an array of objects from my JSON file but I am always facing an error saying: "cannot unmarshal array into Go value of type config.APPConfig".
How can I ensure the configs how my Go struct calls the array of objects within my JSON file?
Here are both my config file in which I set up the Go structs and the JSON file:
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
}
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": "***********"
}
]
Thanks in advance for helping!
Your config json file is an Array of JSON and you are parsing it to struct you need to parse it to array of struct.
To fix your code change the initialization of App to this.
var App []APPConfig
func LoadConfig() error {
return parseJSON("webrtc.json", &App)
}
Here's example full code for it.
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)
}
I am receiving this structure and do not know how to create the go structure to marshal it into:
[
{
"searchinfo": [
{
"PrefProv": "68",
"Language": "Uzbek"
}
]
}
]
How do I define the go structure to unMarshal it into?
Here an example:
package main
import (
"encoding/json"
"fmt"
)
type RawStruct []struct {
Searchinfo []struct {
PrefProv string `json:"PrefProv"`
Language string `json:"Language"`
} `json:"searchinfo"`
}
func main() {
raw_data := `[{"searchinfo":[{"PrefProv":"68","Language":"Uzbek"}]}]`
var rawStruct RawStruct
if err := json.Unmarshal([]byte(raw_data), &rawStruct); err != nil {
panic(err.Error())
}
fmt.Printf("%+v\n", rawStruct)
fmt.Println("---------")
for indexStruct, itemStruct := range rawStruct {
fmt.Printf("Iterating element [%d] of itemStruct: [%+v]\n", indexStruct, itemStruct)
for indexInfo, itemInfo := range itemStruct.Searchinfo {
fmt.Printf("[%d] PrefProv: %s\n", indexInfo, itemInfo.PrefProv)
fmt.Printf("[%d] Language: %s\n", indexInfo, itemInfo.Language)
}
}
}
Result:
[{Searchinfo:[{PrefProv:68 Language:Uzbek}]}]
---------
Iterating element [0] of itemStruct: [{Searchinfo:[{PrefProv:68 Language:Uzbek}]}]
[0] PrefProv: 68
[0] Language: Uzbek
My input json data is this (cannot be changed, from an external resource):
[{
"Url": "test.url",
"Name": "testname"
},{
"FormName": "Test - 2018",
"FormNumber": 43,
"FormSlug": "test-2018"
}]
I have two structs that will always match the data within the array:
type UrlData struct{
"Url" string `json:Url`
"Name" string `json:Name`
}
type FormData struct{
"FormName" string `json:FormName`
"FormNumber" string `json:FormNumber`
"FormSlug" string `json:FormSlug`
}
Obviously the code below will not work, but is it possible at the top level (or otherwise) to declare something like this:
type ParallelData [
urlData UrlData
formData FormData
]
Use a two step process for unmarshaling. First, unmarshal a list of arbitrary JSON, then unmarshal the first and second element of that list into their respective types.
You can implement that logic in a method called UnmarshalJSON, thus implementing the json.Unmarshaler interface. This will give you the compound type you are looking for:
type ParallelData struct {
UrlData UrlData
FormData FormData
}
// UnmarshalJSON implements json.Unmarshaler.
func (p *ParallelData) UnmarshalJSON(b []byte) error {
var records []json.RawMessage
if err := json.Unmarshal(b, &records); err != nil {
return err
}
if len(records) < 2 {
return errors.New("short JSON array")
}
if err := json.Unmarshal(records[0], &p.UrlData); err != nil {
return err
}
if err := json.Unmarshal(records[1], &p.FormData); err != nil {
return err
}
return nil
}
Try it on the playground: https://play.golang.org/p/QMn_rbJj-P-
I think Answer of Peter is awesome.
Option 1:
type ParallelData [
urlData UrlData
formData FormData
]
if you need above structure then you can define it as
type UrlData struct {
Url string `json:"Url,omitempty"`
Name string `json:"Name,omitempty"`
}
type FormData struct {
FormName string `json:"FormName,omitempty"`
FormNumber string `json:"FormNumber,omitempty"`
FormSlug string `json:"FormSlug,omitempty"`
}
type ParallelData struct {
UrlData UrlData `json:"UrlData,omitempty"`
FormData FormData `json:"FormData,omitempty"`
}
In this case, your json will look like
[
{
"UrlData":{
"Url":"test.url",
"Name":"testname"
}
},
{
"FormData":{
"FormName":"Test - 2018",
"FormNumber":"43",
"FormSlug":"test-2018"
}
}
]
Option 2:
You've provide following json:
[
{
"Url":"test.url",
"Name":"testname"
},
{
"FormName":"Test - 2018",
"FormNumber":43,
"FormSlug":"test-2018"
}
]
If your json really look like, then you can use following struct
type UrlData struct {
Url string `json:Url`
Name string `json:Name`
}
type FormData struct {
FormName string `json:FormName`
FormNumber int `json:FormNumber`
FormSlug string `json:FormSlug`
}
type ParallelData struct {
UrlData
FormData
}
For both options, you can Unmarshall your json like this
var parallelData []ParallelData
err := json.Unmarshal([]byte(str), ¶llelData)
if err != nil {
panic(err)
}
fmt.Println(parallelData)
See option 1 in playground
See option 2 in playground
You can unmarshal into a map[string]interface{} for example:
type ParallelData map[string]interface{}
func main() {
textBytes := []byte(`[
{
"Url": "test.url",
"Name": "testname"
},
{
"FormName": "Test - 2018",
"FormNumber": 43,
"FormSlug": "test-2018"
}]`)
var acc []ParallelData
json.Unmarshal(textBytes, &acc)
fmt.Printf("%+v", acc)
}
Output:
=> [map[Url:test.url Name:testname] map[FormName:Test - 2018 FormNumber:43 FormSlug:test-2018]]
Playground
My input json data is this (cannot be changed, from an external resource):
[{
"Url": "test.url",
"Name": "testname"
},{
"FormName": "Test - 2018",
"FormNumber": 43,
"FormSlug": "test-2018"
}]
I have two structs that will always match the data within the array:
type UrlData struct{
"Url" string `json:Url`
"Name" string `json:Name`
}
type FormData struct{
"FormName" string `json:FormName`
"FormNumber" string `json:FormNumber`
"FormSlug" string `json:FormSlug`
}
Obviously the code below will not work, but is it possible at the top level (or otherwise) to declare something like this:
type ParallelData [
urlData UrlData
formData FormData
]
Use a two step process for unmarshaling. First, unmarshal a list of arbitrary JSON, then unmarshal the first and second element of that list into their respective types.
You can implement that logic in a method called UnmarshalJSON, thus implementing the json.Unmarshaler interface. This will give you the compound type you are looking for:
type ParallelData struct {
UrlData UrlData
FormData FormData
}
// UnmarshalJSON implements json.Unmarshaler.
func (p *ParallelData) UnmarshalJSON(b []byte) error {
var records []json.RawMessage
if err := json.Unmarshal(b, &records); err != nil {
return err
}
if len(records) < 2 {
return errors.New("short JSON array")
}
if err := json.Unmarshal(records[0], &p.UrlData); err != nil {
return err
}
if err := json.Unmarshal(records[1], &p.FormData); err != nil {
return err
}
return nil
}
Try it on the playground: https://play.golang.org/p/QMn_rbJj-P-
I think Answer of Peter is awesome.
Option 1:
type ParallelData [
urlData UrlData
formData FormData
]
if you need above structure then you can define it as
type UrlData struct {
Url string `json:"Url,omitempty"`
Name string `json:"Name,omitempty"`
}
type FormData struct {
FormName string `json:"FormName,omitempty"`
FormNumber string `json:"FormNumber,omitempty"`
FormSlug string `json:"FormSlug,omitempty"`
}
type ParallelData struct {
UrlData UrlData `json:"UrlData,omitempty"`
FormData FormData `json:"FormData,omitempty"`
}
In this case, your json will look like
[
{
"UrlData":{
"Url":"test.url",
"Name":"testname"
}
},
{
"FormData":{
"FormName":"Test - 2018",
"FormNumber":"43",
"FormSlug":"test-2018"
}
}
]
Option 2:
You've provide following json:
[
{
"Url":"test.url",
"Name":"testname"
},
{
"FormName":"Test - 2018",
"FormNumber":43,
"FormSlug":"test-2018"
}
]
If your json really look like, then you can use following struct
type UrlData struct {
Url string `json:Url`
Name string `json:Name`
}
type FormData struct {
FormName string `json:FormName`
FormNumber int `json:FormNumber`
FormSlug string `json:FormSlug`
}
type ParallelData struct {
UrlData
FormData
}
For both options, you can Unmarshall your json like this
var parallelData []ParallelData
err := json.Unmarshal([]byte(str), ¶llelData)
if err != nil {
panic(err)
}
fmt.Println(parallelData)
See option 1 in playground
See option 2 in playground
You can unmarshal into a map[string]interface{} for example:
type ParallelData map[string]interface{}
func main() {
textBytes := []byte(`[
{
"Url": "test.url",
"Name": "testname"
},
{
"FormName": "Test - 2018",
"FormNumber": 43,
"FormSlug": "test-2018"
}]`)
var acc []ParallelData
json.Unmarshal(textBytes, &acc)
fmt.Printf("%+v", acc)
}
Output:
=> [map[Url:test.url Name:testname] map[FormName:Test - 2018 FormNumber:43 FormSlug:test-2018]]
Playground
How to unmarshal the json and fill into structures. Like i'm having salesorder and salesorderdetails structures. In json i will have 1 record for salesorder and multiple items for salesorderdetails structure.
Here is the go code i have tried with single item and for multiple items, but working only for single record for salesorderdetails structure.
Gocode:
package main
import (
"encoding/json"
"fmt"
)
type Order struct {
SalesId string `json:"sales_id"`
Customer string `json:"customer_name"`
TotalPrice string `json:"totalprice"`
}
type OrderDetails struct {
DetailId string `json:"detail_id"`
SalesId string `json:"sales_id"`
ItemName string `json:"item_name"`
Qty string `json:"qty"`
Price string `json:"price"`
}
type Temp struct {
Salesorder Order `json:"Salesorder"`
Salesorderdetails OrderDetails `json:"OrderDetails"`
}
func main() {
jsonByteArray := []byte(`[{"Salesorder":{"sales_id":"SOO1","customer_name":"CUST1","totalprice":"200"}, "OrderDetails":{"detailid":"1","sales_id":"SOO1","item_name":"ITEM1","qty":"2","price":"100"}}]`)
//if i use above json it is working and if i use below json its not working
//jsonByteArray := []byte(`[{"Salesorder":{"sales_id":"SOO1","customer_name":"CUST1","totalprice":"200"}, "OrderDetails":{"detailid":"1","sales_id":"SOO1","item_name":"ITEM1","qty":"2","price":"100"},{"detailid":"2","sales_id":"SOO2","item_name":"ITEM2","qty":"3","price":"200"}}]`)
var temp []Temp
err := json.Unmarshal(jsonByteArray, &temp)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", temp)
fmt.Printf("%+v\n ", temp[0].Salesorder.SalesId)
}
Error while using multiple items:
panic: invalid character '{' looking for beginning of object key string
Output while using single item with success:
[{Salesorder:{SalesId:SOO1 Customer:CUST1 TotalPrice:200} Salesorderdetails:{SalesId:SOO1 ItemName:ITEM1 Qty:2 Price:100}}]
SOO1
Fiddle: updated with key in salesorderdetails
https://play.golang.org/p/klIAoNi18r
What you are tying to decode is not valid JSON. This would be valid:
{
"Salesorder": {
"sales_id": "SOO1",
"customer_name": "CUST1",
"totalprice": "200"
},
"OrderDetails": {
"sales_id": "SOO1",
"item_name": "ITEM1",
"qty": "2",
"price": "100"
}
}
But what you are giving is this:
{
"Salesorder": {
"sales_id": "SOO1",
"customer_name": "CUST1",
"totalprice": "200"
},
"OrderDetails": {
"sales_id": "SOO1",
"item_name": "ITEM1",
"qty": "2",
"price": "100"
},
{ // Things become invalid here
"sales_id": "SOO2",
"item_name": "ITEM2",
"qty": "3",
"price": "200"
}
}
It looks like you are trying to give a list of objects, in which case you need to wrap those objects in square brackets [] or you will have to give the second OrderDetails object its own key.
Try this:
package main
import (
"encoding/json"
"fmt"
)
type Order struct {
SalesId string `json:"sales_id"`
Customer string `json:"customer_name"`
TotalPrice string `json:"totalprice"`
}
type OrderDetails struct {
SalesId string `json:"sales_id"`
ItemName string `json:"item_name"`
Qty string `json:"qty"`
Price string `json:"price"`
}
type Temp struct {
Salesorder Order `json:"Salesorder"`
Salesorderdetails []OrderDetails `json:"OrderDetails"`
}
func main() {
jsonByteArray := []byte(`[{"Salesorder":{"sales_id":"SOO1","customer_name":"CUST1","totalprice":"200"}, "OrderDetails":[{"sales_id":"SOO1","item_name":"ITEM1","qty":"2","price":"100"},{"sales_id":"SOO2","item_name":"ITEM2","qty":"3","price":"200"}]}]`)
var temp []Temp
err := json.Unmarshal(jsonByteArray, &temp)
if err != nil {
panic(err)
}
//fmt.Printf("%+v\n", temp)
// Printing all Orders with some details
for _, order := range temp {
fmt.Println("Customer:", order.Salesorder.Customer)
for _, details := range order.Salesorderdetails {
fmt.Printf(" ItemName: %s, Price: %s\n", details.ItemName, details.Price)
}
}
}
.. OrderDetails is an array now