简体   繁体   中英

Golang slice to json array of name value pairs

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))
    }
}

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

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