Search code examples
jsondictionarygomarshalling

converting map to json gives a lot of integers in golang


I'm trying to convert a map to a JSON string. But my code below seems to yield an array of numbers.

Here is my main.go

package main

import (
    "encoding/json"
    "log"
)

type column struct {
  field string
  fieldType string
}

type tblSchema struct {
  tbl string
  columns map[string]column
}
func main() {
    mapper := make(map[string]tblSchema)
    columns := make(map[string]column)
    columns["first"] = column{field:"user_id",fieldType:"int(11)"}
    mapper["t_user"] = tblSchema{tbl:"t_user",columns:columns}
    jsonString, _ := json.Marshal(mapper)
    log.Println(jsonString)
    //log.Println(mapper)
}

This produces the following output

[123 34 116 95 117 115 101 114 34 58 123 125 125]

If I uncomment log.Println(mapper), I get

map[t_user:{t_user map[first:{user_id int(11)}]}]

What am I doing wrong? I expect jsonString to have the following format

{
    "t_user":{
        "tbl":"t_user",
        "columns":{
            "first":{
                "field":"user_id",
                "fieldType":"int(11)"
            }

    }
}

Solution

  • The

    func Marshal(v interface{}) ([]byte, error)
    

    returns []byte so you need to convert it to string:

    log.Println(string(jsonString))
    

    EDIT

    This will yield the desired result

    package main
    
    import (
        "encoding/json"
        "log"
    )
    
    type Column struct {
      Field string
      FieldType string
    }
    
    type TblSchema struct {
      Tbl string
      Columns map[string]Column
    }
    func main() {
        mapper := make(map[string]TblSchema)
        columns := make(map[string]Column)
        columns["first"] = Column{Field:"user_id",FieldType:"int(11)"}
        mapper["t_user"] = TblSchema{Tbl:"t_user",Columns:columns}
        jsonString, _ := json.Marshal(mapper)
        log.Println(string(jsonString))
        log.Println(mapper)
    }