so I have a json with many fields and I am looping through it as suggested by
How effectively to change JSON keys
to delete some of the keys I don’t need. But after deletion, the original values of the existing json was changed, some of them are float numbers it seems and I made a demo to show it.
how can I change this behavior, is the interface{} causing the issue? why is 1684366653200744506 cut off to 1684366653200744400?
thanks
https://go.dev/play/p/X2auWqWB2fL
for reference, the output json is changed to 1684366653200744400
2009/11/10 23:00:00 1684366653200744448.000000
2009/11/10 23:00:00 map[timestamp:1.6843666532007444e+18]
2009/11/10 23:00:00 json Marshal from maps of key string and value interface to batch json for insert to DB
2009/11/10 23:00:00 {"timestamp":1684366653200744400}
>Solution :
I suggest creating a type and removing the field you don’t need.
package main
import (
"encoding/json"
"log"
)
type A struct {
Timestamp int64 `json:"timestamp"`
}
func main() {
jsonBatch := `{"timestamp":1684366653200744506, "todelete":"string value or boolean value"}`
i := A{}
if err := json.Unmarshal([]byte(jsonBatch), &i); err != nil {
log.Println("json UnMarshal from batch json failed")
log.Println(err)
}
dbJsonBatch, err := json.Marshal(i)
if err != nil {
log.Println("json Marshal from batch json failed")
log.Println(err)
}
log.Println("json Marshal from maps of key string and value interface to batch json for insert to DB")
log.Println(string(dbJsonBatch))
}
This prints
2009/11/10 23:00:00 json Marshal from maps of key string and value interface to batch json for insert to DB
2009/11/10 23:00:00 {"timestamp":1684366653200744506}