I am creating a json response in golang.I have a question that i am able to generate a json such as :
{
"Name" : "Country",
"Value" : "abc"
}
The value of name and value can change based on the user and the struct I am using is like:
type xAxis struct {
Name string,
Value string
}
I want my json to look like this:
{
"Country" : "abc"
}
Is it possible to create the json like this?
you can override the way Go's json package marshals a struct by writing a custom MarshalJSON
function:
type xAxis struct {
Name string
Value string
}
func (a xAxis) MarshalJSON() ([]byte, error) {
return json.Marshal(map[string]interface{}{a.Name: a.Value})
}
to try it: http://play.golang.org/p/G_E4IpNYIz
The encoding/json
package allows you to use a map instead of a struct.
That's probably not as performant as structures, but it works.
data := map[string]string {
"Country": "abc",
"Foo": "bar",
}
// Creating JSON from a map
j, err := json.Marshal(data)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(j))
// ==> {"Country":"abc","Foo":"bar"}
// Creating map from JSON
var data2 map[string]string
err = json.Unmarshal(j, &data2)
if err != nil {
log.Fatal(err)
}
fmt.Println(data2)
// ==> map[Country:abc Foo:bar]