0

I have to format a json in go and I have some problems. the string literal that I have used in java is the following:

 String jsonString= "{\"stream\":\"temperatura2\",\r\n" + "\"sensor\":\"ec6c613a-66b4-4584-fb37-5f7cac130f7d\",\r\n" + "\"values\":[{\"time\":\"2019-03-10T11:30:00Z\",\"components\":{\"alfanum\":\"99.0\"}}]}\r\n"; 

So I created this struct:

type YuccaDataStream struct { Stream string `json:"stream"` Sensor string `json:"sensor"` Values []struct { Time time.Time `json:"time"` Components struct { Alfanum string `json:"alfanum"` } `json:"components"` } `json:"values"` } 

Is that struct correct? I don't know how to create an instance of that struct and fill it with the current time.

3
  • Possible duplicate of stackoverflow.com/questions/26866879/…. Commented Nov 28, 2019 at 20:35
  • use named types. this is insane to manually initialize. Commented Nov 28, 2019 at 20:40
  • I'm trying to learn go and I don't know named types, I will look. Thank you :) Commented Nov 28, 2019 at 21:04

2 Answers 2

1

don't do that.

package main import ( "fmt" "time" ) func main() { fmt.Println("Hello, playground") y := YuccaDataStream{ Values: []struct { Time time.Time Components struct { Alfanum string } }{ // struct { Time time.Time Components struct { Alfanum string } }{Time: time.Now(), Components: struct{ Alphanum string }{Alphanum: "aaa"}}, // struct { Time time.Time Components struct { Alfanum string } }{Time: time.Now(), Components: struct{ Alphanum string }{Alphanum: "bbb"}}, // }, } } type YuccaDataStream struct { Stream string `json:"stream"` Sensor string `json:"sensor"` Values []struct { Time time.Time `json:"time"` Components struct { Alfanum string `json:"alfanum"` } `json:"components"` } `json:"values"` } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. Looks very complicated.
1

How about this:

package main import ( "fmt" "time" "encoding/json" ) type YuccaDataStream struct { Stream string `json:"stream"` Sensor string `json:"sensor"` Values []Value `json:"values"` } type Value struct { Time time.Time `json:"time"` Components `json:"components"` } type Components struct { Alfanum string `json:"alfanum"` } func main() { data := []byte(`{"stream": "temperatura2","sensor": "ec6c613a-66b4-4584-fb37-5f7cac130f7d","values": [{"time": "2019-03-10T11:30:00Z","components": {"alfanum": "99.0"}}]}`) var unmarshaled YuccaDataStream err := json.Unmarshal(data, &unmarshaled) if err != nil { panic(err) } fmt.Printf("%v",unmarshaled) } 

try in go playground

2 Comments

Thank you. How do I use Yr syntax to insert for example the current time and then marshal?
If you want to marshal you can create a variable of type YuccaDataStream, fill the data and in the time field use time.Now.UTC(). then you can use json.Marshal.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.