Home > Enterprise >  How to serialize a dictionary in golang
How to serialize a dictionary in golang

Time:03-01

I try to replicate this body form in order to use it in a request:

{"Responses":[{"type":"DROP_DOWN","value":"0"}]}

so what im doing is :

type FruitBasket struct {
        Name5 []string `json:"Responses"`
        
    }
form := payload{
        Name5: []string{"type", "value"},
    }
    jsonData, err := json.Marshal(form)
    fmt.Println(string(jsonData))

But i can't find a way to complete the body in the brackets

CodePudding user response:

You need to use the Unmarshal function from "encoding/json" package and use a dummy struct to extract the slice fields

// You can edit this code!
// Click here and start typing.
package main

import (
    "encoding/json"
    "fmt"
)

func main() {

    str := `{"Responses":[{"type":"DROP_DOWN","value":"0"}]}`

    type Responses struct {
        Type  string `json:"type"`
        Value string `json:"value"`
    }

    // add dummy struct to hold responses
   type Dummy struct {
        Responses []Responses `json:"Responses"`
    }
    var res Dummy
    err := json.Unmarshal([]byte(str), &res)
    if err != nil {
        panic(err)
    }
    fmt.Println("%v", len(res.Responses))
    fmt.Println("%s", res.Responses[0].Type)
    fmt.Println("%s", res.Responses[0].Value)

}

CodePudding user response:

JSON-to-go is a good online resource to craft Go date types for a particular JSON schema.

Pasting your JSON body & extracting out the nested types you could use the following types to generate the desired JSON schema:

// types to produce JSON:
//
//    {"Responses":[{"type":"DROP_DOWN","value":"0"}]}

type FruitBasket struct {
    Response []Attr `json:"Responses"`
}

type Attr struct {
    Type  string `json:"type"`
    Value string `json:"value"`
}

to use:

form := FruitBasket{
    Response: []Attr{
        {
            Type:  "DROP_DOWN",
            Value: "0",
        },
    }
}

jsonData, err := json.Marshal(form)

working example: https://go.dev/play/p/SSWqnyVtVhF

output:

{"Responses":[{"type":"DROP_DOWN","value":"0"}]}

CodePudding user response:

Your struct is not correct. Your title want dictionary, but you write an array or slice of string.

Change your FruitBasket struct from this:

type FruitBasket struct {
    Name5 []string `json:"Responses"`
}

to this

type FruitBasket struct {
    Name5 []map[string]interface{} `json:"Responses"`
}

map[string]interface{} is dictionary in go

here's the playground https://go.dev/play/p/xRSDGdZYfRN

  • Related