duanneng2014 2014-01-24 22:12
浏览 516
已采纳

json.Marshal返回奇怪的结果

I'm trying to convert go structures to JSON. I thought I knew how to do it, but I'm confused by the output of this program. What am I missing?

package main
import "fmt"
import "encoding/json"

type Zoo struct {                                                                       
    name string
    animals []Animal
}
type Animal struct {
    species string
    says string
}

func main() {
    zoo := Zoo{"Magical Mystery Zoo",                                                   
         []Animal {
            { "Cow", "Moo"},
            { "Cat", "Meow"},
            { "Fox", "???"},
        },
    }
    zooJson, err := json.Marshal(zoo)
    if (err != nil) {
        fmt.Println(err)
    }

    fmt.Println(zoo)
    fmt.Println(zooJson)
}

Output:

{Magical Mystery Zoo [{Cow Moo} {Cat Meow} {Fox ???}]}
[123 125]

Expected Output (something along the lines of):

{Magical Mystery Zoo [{Cow Moo} {Cat Meow} {Fox ???}]}
{
    "name" : "Magical Mystery Zoo",
    "animals" : [{
             "name" : "Cow",
             "says" : "moo"
         }, {
             "name" : "Cat",
             "says" : "Meow"
         }, {
             "name" : "Fox",
             "says" : "???"
         }
    ]
 }

Where is [123 125] coming from?

Appreciate the help!

  • 写回答

2条回答 默认 最新

  • duanlujiaji10335 2014-01-24 22:23
    关注

    The result of marshaling is []byte so 123 and 125 is ascii for { and }

    Struct fields have to be exported for marshaling to work:

    Each exported struct field becomes a member of the object

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 SQL Server下载
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件
  • ¥15 不同系统编译兼容问题
  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求