Add vrackets to json object

Hello everyone,

I’m new with Go and i’m struggling a little with JSON objects.

I’m programmin an app to trasfert received data to a client.

the client is accepting only JSON objects with brackets outside, like this:

[{“variable”:“temperature”,“fields”:{“value”:“25”,“quality”:5},“timestamp”:“2021-03-23T17:23:51Z”}]

I’m able to create JSON objects with the code attached that look like this :

{“variable”:“temperature”,“fields”:{“value”:“25”,“quality”:5},“timestamp”:“2021-03-23T17:23:51Z”}

I’m looking for a way to add those brackets to my JSON objects automatically.

This is my code

type epde_fields struct {
	Value   string `json:"value"`
	Quality int32  `json:"quality"`
}

type epde_format struct {
	Variable  string      `json:"variable"`
	Fields    epde_fields `json:"fields"`
	Timestamp string      `json:"timestamp"`
}

func SendData(xcontext *appcontext.Context, params ...interface{}) (bool, interface{}) {
	if len(params) < 1 {
		// We didn't receive a result
		return false, nil
	}

	token := get_token()
	//print token
	fmt.Println("token has been received:", token)

	sensor_name := extractValue(params[0].(string), "name")
	value := extractValue(params[0].(string), "value")
	t := extractValue(params[0].(string), "origin")

	cv, _ := strconv.ParseInt(t, 10, 64)
	timestamp := time.Unix(cv/1000000000, 0)

	field := epde_fields{
		Value:   value,
		Quality: 5,
	}

	tmp := epde_format{
		Variable:  sensor_name,
		Fields:    field,
		Timestamp: timestamp.Format("2006-01-02T15:04:05Z"),
	}
	payload, err := json.Marshal(tmp)
	if err != nil {
		fmt.Println("error:", err)
	}

	fmt.Println(string(payload))

}

Can you help me with this issue please ?

Thank you

Howabout wrap it into either an []epde_format or [1]epde_format and marshal that?

Thank you @skillia.

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