GoLang_Nested Structs Explicit Assignment

I am working on a Module for whihc i need to output a jSON formatted data. I have the structure for the JSON output and just need to assign values but unable to do so.
Can anyone suggest how to do the below.

JSON structure

type FinalJson struct {
	Stat        string `json:"status"`
	RAR struct {
		Stay bool `json:"Stay"`
		Rooms    []struct {
			Description    string  `json:"description"`
			Accessible     bool    `json:"accessible"`
			Rates          []struct {
				NightRatesBeforeTax []float64 `json:"nightRatesBeforeTax"`
				NightRatesAfterTax  []float64 `json:"nightRatesAfterTax"`
				RatePlanID          string    `json:"ratePlanId"`
				CurrencyCode        string    `json:"currencyCode"
				TaxList []struct {
					TaxType    string `json:"taxType"`
					TaxPercent string `json:"taxPercent"`
				} `json:"taxList"`

I have more nested structs in this, only looking a way out to assign values to them. The data which i need to assign will be some hard coded and some coming from other REsT Services.

Can anyone help on this?

Can you please try to use proper markdown to embed your code in your post such that it is easily readable?

Also a playground link to some code that shows what you have tried to actually assign data would help us a lot to help you.

Or at the very least properly formatted code with a main function that we can run locally and shows what you have tried to assign data.

But from what I do see right now, I can tell you, that it will be much easier, when you extract the anonymous structs you have now, into own types. If you do not extract them, you’ll need to repeat their definition in each and every literal assignment.

1 Like
package main

import (

//structure for Final Json Output

type FinalJson struct {
	Status        string `json:"status"`
	RoomsAndRates struct {
		FreeStay bool `json:"freeStay"`
		Rooms    []struct {
			Description    string  `json:"description"`
			RoomTypeCode   string  `json:"roomTypeCode"`
			NonSmoking     bool    `json:"nonSmoking"`
			ShortName      string  `json:"shortName"`
			MaxOccupancy   int     `json:"maxOccupancy"`
			InventoryCount int     `json:"inventoryCount"`
			LowRate        float64 `json:"lowRate"`
			BedType        string  `json:"bedType"`
			Accessible     bool    `json:"accessible"`
			Rates          []struct {
				NightRatesBeforeTax []float64 `json:"nightRatesBeforeTax"`
				NightRatesAfterTax  []float64 `json:"nightRatesAfterTax"`
				RatePlanID          string    `json:"ratePlanId"`
				CurrencyCode        string    `json:"currencyCode"`
				DateRateMap         struct {
					Zero3032018 float64 `json:"03/03/2018"`
					Zero3042018 float64 `json:"03/04/2018"`
				} `json:"dateRateMap"`
				TaxList []struct {
					TaxType    string `json:"taxType"`
					TaxPercent string `json:"taxPercent"`
				} `json:"taxList"`
				CancelPolicy      string      `json:"cancelPolicy"`
				DepositPolicy     string      `json:"depositPolicy"`
				NightBeforeTaxMin float64     `json:"nightBeforeTaxMin"`
				NightAfterTaxMin  float64     `json:"nightAfterTaxMin"`
				NightBeforeTaxMax float64     `json:"nightBeforeTaxMax"`
				NightAfterTaxMax  float64     `json:"nightAfterTaxMax"`
				AverageBeforeTax  float64     `json:"averageBeforeTax"`
				AverageAfterTax   float64     `json:"averageAfterTax"`
				TotalBeforeTax    float64     `json:"totalBeforeTax"`
				TotalAfterTax     float64     `json:"totalAfterTax"`
				Qualified         bool        `json:"qualified"`
				Filtered          bool        `json:"filtered"`
				Express           bool        `json:"express"`
				QualPointsEarned  int         `json:"qualPointsEarned"`
				AutoEnroll        bool        `json:"autoEnroll"`
				AlternateRate     bool        `json:"alternateRate"`
				CorpCode          interface{} `json:"corpCode"`
				CugRate           bool        `json:"cugRate"`
				PacRatePlan       bool        `json:"pacRatePlan"`
				PacPoints         interface{} `json:"pacPoints"`
				TotalPacPoints    interface{} `json:"totalPacPoints"`
				FnsRatePlan       bool        `json:"fnsRatePlan"`
				FnsPoints         interface{} `json:"fnsPoints"`
				TotalFnsPoints    interface{} `json:"totalFnsPoints"`
			} `json:"rates"`
		} `json:"rooms"`
		RatePlans []struct {
			Rooms               []string    `json:"Rooms"`
			RoomsRate           []float64   `json:"RoomsRate"`
			LowRate             float64     `json:"LowRate"`
			RatePlanCode        string      `json:"RatePlanCode"`
			CancelCode          interface{} `json:"CancelCode"`
			CancelPenalty       string      `json:"CancelPenalty"`
			RatePlanDescription string      `json:"RatePlanDescription"`
			RatePlanName        string      `json:"RatePlanName"`
			AlternateRate       bool        `json:"alternateRate"`
			CorpCode            interface{} `json:"corpCode"`
			AutoEnroll          bool        `json:"autoEnroll"`
			DepositPolicy       []string    `json:"depositPolicy"`
			PacPoints           interface{} `json:"pacPoints"`
			PacRatePlan         bool        `json:"pacRatePlan"`
			CugRate             bool        `json:"cugRate"`
			FnsRatePlan         bool        `json:"fnsRatePlan"`
			FnsPoints           interface{} `json:"fnsPoints"`
			StrikeOutRate       interface{} `json:"strikeOutRate"`
			StrikeOutRatePlan   interface{} `json:"strikeOutRatePlan"`
		} `json:"ratePlans"`
	} `json:"roomsAndRates"`

func main() {

	//XMl file

	xmlFile, err := ioutil.ReadFile("TEst.xml")
	if err != nil {

	xmlStr := string(xmlFile) // convert content to a 'string'

	rawXmlData := xmlStr

	var outData Envelope //Envelope is the structure for XML:  removed from this sample code

	xml.Unmarshal([]byte(rawXmlData), &outData)

	//outData has the raw data from the xml Response

	//Now i want to iterate over this raw data and map ceratin data to json output with some logic involved
	//I am unable to directly assign values to structs nested inside

	result := &FinalJson{
		Status: "OK",
	result.RoomsAndRates.FreeStay = true //Works fine

	//Unable to do something like
	result.RoomsAndRates.Rooms[0].Description = "Spmething"

	jsonData, _ := json.Marshal(result)

Her you go commented in the code what i am looking for…Any help would be appreciated…

Sorry, but I can not run your example, as the XML is missing.

Also please try to produce some kind of sscce.

But you say

//Unable to do something like
result.RoomsAndRates.Rooms[0].Description = "Spmething"

Of course not. since result.RoomsAndRates.Rooms is nil at this point, you need to append to it:

result.RoomsAndRates.Rooms = append(result.RoomsAndRates.Rooms, struct{…}{Description: "Spmething"}

If you had extracted the anonymous structs as I said previously, you simply could do

result.RoomsAndRates.Rooms = append(result.RoomsAndRates.Rooms, RoomType{Description: "Spmething"}
1 Like

Thanks for taking time and replying.

I think i can over come this difficulty by using Maps. My Idea to create a map inside a map and finally marshal it to get the required JSON. That way i have full control on what gets inside the map keys and values which will be part of the output JSON.
That way i dont have to define the structs. Any suggestions on this? See the below sample whihc works.

I have no idea on performance using Maps or the Structs the way u r suggesting.

//Below Sample Code
package main

func main() {
    testMap := make(map[string]interface{})

	 innerMap := make(map[string]string)




   out,_ :=json.Marshal(testMap)

Please use the “Preformatted text” boxes in your posts. That makes it much easier to read the code. Select any text you want to be inside one of the yellow boxes and press the button that looks like “</>” in the editor. :slight_smile:
I have edited your posts to fix the formatting now :+1:


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.