When I am calling an endpoint point getting below two json. In response, I need to send one json response. In Json1 value
is empty and need to get the value from Json2.
I am unable to get attributes with in LayoutSections
Json:1
{
"Name": "VisitDoctorLayout",
"Kind": "Visit",
"layoutsections": [
{
"label": "AccountInformation",
"style": "TwoColumnsTopToBottom",
"layoutcolumns": [
{
"layoutitems": [
{
"behavior": "edit",
"name": "firstname",
"type": "string",
"label": "first Name",
"value": ""
},
{
"behavior": "Required",
"name": "lastname",
"type": "string",
"label": "Last Name",
"value": ""
}
]
}
]
}
]
}
Json:2
{"firstname":"ABC",
"lastname":"EFZ"
}
My sruct is something like below
type Layout struct {
ID string `json:"ID"`
Name string `json:"name"`
Kind string `json:"kind"`
Namespace string `json:"namespace"`
LayoutSections []LayoutSections `json:"layoutsections"`
}
type LayoutSections struct {
Label string `json:"label"`
Style string `json:"style"`
LayoutColumns []LayoutColumns `json:"layoutcolumns"`
}
type LayoutColumns struct {
LayoutItems []LayoutItems `json:"layoutitems"`
}
type LayoutItems struct {
Behavior string `json:"behavior"`
Name string `json:"name"`
Type string `json:"type"`
Label string `json:"label"`
Value string `json:"value"`
}
I'm not sure If I got your request right but here's how I "mapped" the data from Json2
to Json1
.
// Added this for the inserter json (Json2)
type Inserter struct {
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
}
var dat Layout
var ins Inserter
func main() {
if err := json.Unmarshal(json1, &dat); err != nil {
panic(err)
}
if err := json.Unmarshal(json2, &ins); err != nil {
panic(err)
}
for sk, sec := range dat.LayoutSections {
for ck, col := range sec.LayoutColumns {
for ik, item := range col.LayoutItems {
itemPointer := &dat.LayoutSections[sk].LayoutColumns[ck].LayoutItems[ik]
switch item.Name {
case "firstname":
// Setting the FirstName value:
itemPointer.Value = ins.FirstName
case "lastname":
// Setting the LastName value:
itemPointer.Value = ins.LastName
}
}
}
}
}
Basically you can just dig into the:Layout
> LayoutSections
> LayoutColumns
> LayoutItems
Then check for the items you want to change, in our case firstname
& lastname
. And finally just set their Value
to what the Inserter
json (Json2) contains.
And here's the working Example with all the details.