I need to create a list of values from JSON input. For example, if the input is: (this is a file. The content below is mentioned for this question)
x := `[
{
"customer_id": "g62"
},
{
"customer_id": "b23"
},
{
"customer_id": "a34"
},
{
"customer_id": "c42"
}
]`
The output needs to be in json format: {"Customer_id":["g62","b23","a34","c42"]}
I have come up with a code which gives out following: [{"Tenant_id":"7645","Customer_id":["g62","b23","a34","c42"]}]
I have an extra field of Tenant_id and I don't think this code is efficient since I need to create a map and then a list to achieve this. I looked for many online examples but I couldn't find any specific one which can help me do better. My goal here is to make it efficient and git rid of an extra field "tenant_id". Any comment or help is appreciated.
Note: I made use of tenant_id since I needed to have a key for my map. I am looking for an alternative solution or idea!
The code below is working:
package main
import (
"encoding/json"
"fmt"
)
type InpData struct {
Tenant_id string
Customer_id []string
}
type InpList []InpData
func main() {
x := `[
{
"customer_id": "g62"
},
{
"customer_id": "b23"
},
{
"customer_id": "a34"
},
{
"customer_id": "c42"
}
]`
var v InpList
if err := json.Unmarshal([]byte(x), &v); err != nil {
fmt.Println(err)
}
fmt.Printf("%+v", v)
fmt.Println("\nJson out of list:")
fmt.Println()
j, err := json.Marshal(v)
if err != nil {
fmt.Printf("Error: %s", err.Error())
} else {
fmt.Println(string(j))
}
}
func (v *InpList) UnmarshalJSON(b []byte) error {
// Create a local struct that mirrors the data being unmarshalled
type mciEntry struct {
Tenant_id string `json:"tenant_id"`
Customer_id string `json:"customer_id"`
}
var tenant_id string
tenant_id = "7645"
type InpSet map[string][]string
var entries []mciEntry
// unmarshal the data into the slice
if err := json.Unmarshal(b, &entries); err != nil {
return err
}
tmp := make(InpSet)
// loop over the slice and create the map of entries
for _, ent := range entries {
tmp[tenant_id] = append(tmp[tenant_id], ent.Customer_id)
}
fmt.Println()
tmpList := make(InpList, 0, len(tmp))
for key, value := range tmp {
tmpList = append(tmpList, InpData{Tenant_id: key, Customer_id: value})
}
*v = tmpList
return nil
}