Program not printing whole json data as struct

hello everybody,
can anyone help me to get fix this program,it is running correctly but giving wrong output.
I have a struct there and when i run this program it is printing

Output:{todo {0001-01-01 00:00:00 +0000 UTC Assad lunch from home false}}

rather than
Output:{todo {0001-01-01 00:00:00 +0000 UTC Assad lunch from home today false 3 pm}}

below is the code:

package main

import (
“encoding/json”
“fmt”
“time”
)

type ServiceStruct struct {
Todo string json:"todo"

DataStruct struct {
CreationDateTime   	time.Time `json:"creation_dt"`
Title 			string    `json:"title"`
Description  		string    `json:"description"`
DueDateTime  		string    `json:"due_date_time"`
CompletionDateTime  	string    `json:"completion_date_time"`	
CompletionStatus 	bool      `json:"completion_status"`

}
}

func main() {

x := `{
	"Todo": "todo",
"DataStruct": {
"CreationDateTime": "time.Now()",
    "Title":   "Assad",
	"Description": "lunch from home",
	"DueDateTime": "today",
	"CompletionStatus": false,
	"CompletionDateTime": "3 pm"

}
}`

ex := ServiceStruct{}
 json.Unmarshal([]byte(x), &ex)

fmt.Println(ex)

}

In your typedefinition you specify the JSON keys differently then how you use them in the actual JSON, after fixing them (and omitting some fields that are obviously not a time.Time), it works as expected.

how can I fix this? can you help me

Fix the keys you use. Either make the JSON match your structs definition or make the struct match the keys you want to use.

I am using the same keys as defined in struct and using them in initializing x, if am changing the order the results are still same

struct:
DataStruct struct {
CreationDateTime time.Time json:"creation_dt"
Title string json:"title"
Description string json:"description"
DueDateTime string json:"due_date_time"
CompletionDateTime string json:"completion_date_time"
CompletionStatus bool json:"completion_status"
}

x := `{
“Todo”: “todo”,
“DataStruct”: {
“CreationDateTime”: “time.Now()”,
“Title”: “Assad”,
“Description”: “lunch from home”,
“DueDateTime”: “today”,
“CompletionStatus”: false,
“CompletionDateTime”: “3 pm”
}

In your struct definition you use `json:"foo"` to set the keyname to use, though in the JSON to parse you use the field names from the struct.

I am pretty sure that whatever you type after json: must match the name in the json string (x). Example, if you type json:creation_dt the json string must contain a field called creation_dt. See below:

got it, Thanks for your help @NobbZ @Hultan

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