Suppose I have such a json file. I want to delete one of the window, image or text fields according to the user's choice and print the rest of the content to a different file.
{
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
For example, I want to delete the window field I want to write this content to a different file.
I'm stuck and have no idea how to do it. It is easy to write to another file, but I have no way of knowing how to delete a fiel
Can you suggest me some approaches that make sense?
{
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
CodePudding user response:
As per my understanding, we can follow two approaches here.
First We can Unmarshal JSON
data into the Go language struct
Second, we can UnmarshalJSON
data into the Go language map
because I don't know the struct so we can go with the map.
You can try the first approach also for learning purposes but that will only work with proper struct.
data := []byte(`{"window":{"title":"Sample Konfabulator Widget","name":"main_window","width":500,"height":500},"image":{"src":"Images/Sun.png","name":"sun1","hOffset":250,"vOffset":250,"alignment":"center"},"text":{"data":"Click Here","size":36,"style":"bold","name":"text1","hOffset":250,"vOffset":100,"alignment":"center","onMouseUp":"sun1.opacity = (sun1.opacity / 100) * 90;"}}`)
var v interface{}
err := json.Unmarshal(data, &v)
if err != nil {
fmt.Println("error:", err)
}
m := v.(map[string]interface{})
// delete window
delete(m, "window")
then you can again marshal to JSON and write to file
b, err := json.Marshal(m)
if err != nil {
fmt.Println("error:", err)
}
fmt.Println(string(b))