how to unmarshal json and fill into structures in golang - arrays

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

Related

How to unmarshal objects inside array

I am trying to get access to object's values inside of array
[
{
"name": "London",
"lat": 51.5073219,
"lon": -0.1276474,
"country": "GB",
"state": "England"
}
]
I use this code to unmarshal it
content, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}
var data []ResponseData
err = json.Unmarshal(content, &data)
if err != nil {
log.Fatal(err)
}
This is my struct
type ResponseData struct {
Name string `json:"name"`
Lat float32 `json:"lat"`
Lon float32 `json:"lon"`
Country string `json:"country"`
State string `json:"state"`
}
I need to simply fmt.Println(data.Lat, data.Lon) later.
The code you presented should unmarshal your JSON successfully; the issue is with the way you are trying to use the result. You say you want to use fmt.Println(data.Lat, data.Lon) but this will not work because data is a slice ([]ResponseData) not a ResponseData. You could use fmt.Println(data[0].Lat, data[0].Lon) (after checking the number of elements!) or iterate through the elements.
The below might help you experiment (playground - this contains a little more content than below):
package main
import (
"encoding/json"
"fmt"
"log"
)
const rawJSON = `[
{
"name": "London",
"lat": 51.5073219,
"lon": -0.1276474,
"country": "GB",
"state": "England"
}
]`
type ResponseData struct {
Name string `json:"name"`
Lat float32 `json:"lat"`
Lon float32 `json:"lon"`
Country string `json:"country"`
State string `json:"state"`
}
func main() {
var data []ResponseData
err := json.Unmarshal([]byte(rawJSON), &data)
if err != nil {
log.Fatal(err)
}
if len(data) == 1 { // Would also work for 2+ but then you are throwing data away...
fmt.Println("test1", data[0].Lat, data[0].Lon)
}
for _, e := range data {
fmt.Println("test2", e.Lat, e.Lon)
}
}

Create go structure to accept json with anonymous top level items

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

unmarshal json array of records with inner arrays (all integers) [duplicate]

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), &parallelData)
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

Unmarshal 2 different structs in a slice

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), &parallelData)
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 put data in a struct with Golang?

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

Resources