如何在Go中解码json

I have a json look like this

[{"name":"Name1","age":20},{"name":"Name2","age":29}]

And I want to decode it to map look like this

map[map["name":"Name1" ....] ,map["name":"Name2",....]]

In my case I have a logic look like this

bt:= []byte(metadatas[0])
var dat interface{}
if err := json.Unmarshal(bt, dat); err != nil {
    panic(err)
}
fmt.Println(dat)

and as a response I am getting

[map["name":"Name1" ....] ,map["name":"Name2",....]]

How can I get a map instead of

By definition map is a data structure that keeps a reference to specific values using some predefined keys.

In your case, you're having a data structure called collection (array of maps). If you want to keep your collection items as another map values the easiest way to achieve this is to transform your collection into map using indexes of the array (collection) as keys.

However I'm not sure you would be able to do it straight-head during your json.Unmarshal without applying some additional transformations

A target data structure for unmarshaling can be defined as val := []map[string]interface{}{}:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    input := []byte(`[{"name":"Name1","age":20},{"name":"Name2","age":29}]`)
    val := []map[string]interface{}{}
    if err := json.Unmarshal(input, &val); err != nil {
        panic(err)
    }
    fmt.Printf("%v
", val)
}

Go Playgroung

This gives us a slice of maps. If you want to put those maps inside another map, there should be a key for elements of that map (like their indexes in the slice).

I have already fix this problem, Here is my logic

type Meta struct {
    Name string `json:"name"`
    Age int `json:"age"`
}

type Metadata struct {
    Collection []Meta
}


bt:= []byte(metadatas[0])
dat := make([]Meta, 0)
if err := json.Unmarshal(bt, &dat); err != nil {
    panic(err)
}

And as a response I am getting array with objects