J. Doe
J. Doe

Reputation: 55

How do I add brackets within JSON serialization?

I am trying to send a post request to a API endpoint. The endpoint does not work without brackets in the JSON data.

map1: = map[string] map[string] interface {} {}
map2: = map[string] interface {} {}
map2["firstObject"] = "value1"
map2["secondObject"] = "value2"

map1["jsonName"] = map2
b, err: = json.Marshal(map1)
if err != nil {
    panic(err)
}

fmt.Println(string(b)) // outputs: {"jsonName":{"firstObject":"value1","secondObject":"value2"}}

I need the output to be: {"jsonName":[{"firstObject":"value1","secondObject":"value2"}]}

However, I am getting this: {"jsonName":{"firstObject":"value1","secondObject":"value2"}}

Upvotes: 0

Views: 195

Answers (1)

Chris Heald
Chris Heald

Reputation: 62688

Your indicated payload is passing a map as the value of jsonName, when the API needs an array of maps.

It may help if you create the inner map first:

map2 := map[string]interface{}{
    "firstObject":  "value1",
    "secondObject": "value2",
}

Then create your outer map as a map of string => []interface{}, giving your key and value:

map1 := map[string][]interface{}{
    "jsonName": []interface{}{map2},
}

You can do it all in one shot as:

map1 := map[string][]interface{}{
    "jsonName": []interface{}{
        map[string]interface{}{
            "firstObject":  "value1",
            "secondObject": "value2",
        },
    },
}

Upvotes: 1

Related Questions