0

I have a slice of the following structs.

type ParamStruct struct {
    Paramname  string
    Paramvalue interface{}
}

The value can be an int, float of string. I need to convert the slice that looks something like this [{name1 95} {name2 someStrValue} {name3 someOtherStrValue}] to a JSON array that looks like the following.

[
{ "name1": 1 },
{ "name2": "someStrValue"},
{ "name3": "someOtherStrValue"}
]

I tried marshaling using the default function and get a JSON output like this..

[{"Paramname":"name1","Paramvalue":95},{"Paramname":"name2","Paramvalue":"someStrValue"},{"Paramname":"name3","Paramvalue":"someOtherStrValue"}]

The output JSON has to be name-value pairs like it is shown above. Any suggestions on how I can get the JSON output in the desired format?

Here is the complete code example

package main

import (
    "encoding/json"
    "fmt"
)

type ParamStruct struct {
    Paramname  string
    Paramvalue interface{}
}

func main() {
    paramlist1 := make([]ParamStruct, 3)

    paramlist1[0].Paramname = "name1"
    paramlist1[0].Paramvalue = 95
    paramlist1[1].Paramname = "name2"
    paramlist1[1].Paramvalue = "someStrValue"
    paramlist1[2].Paramname = "name3"
    paramlist1[2].Paramvalue = "someOtherStrValue"
    fmt.Println(paramlist1)
    js, err := json.Marshal(paramlist1)
    if err != nil {
        fmt.Printf("Error: %s", err.Error())
    } else {
        fmt.Println(string(js))
    }
}
1
  • Without any custom marshalling it is not possible to transform the list of structs to key value pairs. Commented Apr 13, 2021 at 5:13

1 Answer 1

4

You could implement the json.Marshaler interface.

For example:

type ParamStruct struct {
    Paramname  string
    Paramvalue interface{}
}

func (ps ParamStruct) MarshalJSON() ([]byte, error) {
    return json.Marshal(map[string]interface{}{ps.Paramname: ps.Paramvalue})
}

https://play.golang.org/p/sUsR-FMZQmq

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.