简体   繁体   中英

Marshall MAP to JSON

I'm in the process of getting started with moving from Python to GoLang and I'm trying to get my head around datatype. I need to marshall a map to the following JSON but I'm not quite sure how my map should be constructed.

This is what I've tried but its not working for me.

data := map[string]string{"Offset": "0", "Properties": map[string]string{"key": "Type", "value": "User"}, "Category": "all", "Locations": map[string]string{}, "Accounts": "100" }
data_json, _ := json.Marshal(data)
fmt.Println(string(data_json))

Desired Result:

{
"Locations": [],
"Dates": [],
"Properties": [
  {
    "key": "Type",
    "value": "User"
  }
 ],
 "Category": "all",
 "Accounts": [],
 "Offset": 0,
 "Limit": 100
}

The issue is that you're claiming to write a map of strings to strings (key is a string AND value is a string). But you have the key/value pair: "Properties": map[string]string{"key": "Type", "value": "User"} , and that value is not a string, its another map. If you define the data as a map of strings to interfaces, it should work. That would look more like this:

data := map[string]interface{}{"Offset": "0", "Properties": map[string]string{"key": "Type", "value": "User"}, "Category": "all", "Locations": map[string]string{}, "Accounts": "100" }

Here is a working example: http://play.golang.org/p/HjHH463J_r

If you're unsure what interfaces are and why they work, the documentation explains it pretty well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM