I can create this data structure in Python really easily:
data = {'Locations': [],
'Dates': [],
'Properties': [{'key': 'data1', 'value': 'data2'}],
'Category': 'all'}
Which can then be marshalled to JSON in Python just as easily. e.g.
print json.dumps(data)
{"Category": "all", "Dates": [], "Locations": [], "Properties": [{"value": "data2", "key": "data1"}]}
However, I'm tearing my hair out trying to create the same structure then convert it to JSON in Go. Go looks to be very promising and just what I need for creating cross platform applications, but boy this stuff seems to be frustratingly difficult.
This is what I've tried, however I cant get the structure to include the square brackets that should surround the properties element.
import (
"fmt"
"encoding/json"
)
func main() {
data := map[string]interface{}{"Offset": "0", "Properties": map[string]string{"value": "data2", "key": "data1"}, "Category": "all", "Locations": []string{}, "Dates": []string{} }
data_json, _ := json.Marshal(data)
fmt.Println(string(data_json))
}
Which outputs:
{"Category":"all","Dates":[],"Locations":[],"Offset":"0","Properties":{"key":"data1","value":"data2"}}
Heres a demo: http://play.golang.org/p/49Kytg6v_C
You just need to create a slice of map[string]string
:
data := map[string]interface{}{
"Offset": "0",
"Properties": []map[string]string{{"value": "data2", "key": "data1"}},
"Category": "all",
"Locations": []string{},
"Dates": []string{},
}
While OneOfOne's solution works in a literal sense, with Go's static typing you likely want a struct.
// The `json:"stuff"` will cause it to use that json tag when reading or writing json.
type Property struct {
Key string `json:"key"`
Val string `json:"value"`
}
// ,omitempty allows it to ignore the empty string "" when writing json,
// I put this here because one of your json examples had no Offset field
// you can do this with other fields too.
type MyType struct {
Offset string `json:",omitempty"`
Properties []Property
Category string
Locations []string
Dates []string
}
Of course, you could also consider using built-in or custom Go types for some of those fields, such as using a []time.Time
for the Dates field. This makes it more difficult to just read/write arbitrary json ad-hoc or on the fly, but since you need to have some logic somewhere to interpret those fields, in Go it generally makes much more sense to treat it as a struct most of the time.
To read in/put out the json, you would then do
import "encoding/json"
//...
stuff := MyType{}
json.Unmarshal(myJsonData, &stuff)
// stuff is now { [{data1 data2}] all [] []}
out,_ := json.Marshal(stuff)
// string(out) is now {"Properties":[{"key":"data1","value":"data2"}],
// "Category":"all","Locations":[],"Dates":[]}
Playground: http://play.golang.org/p/jIHgXmY13R