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 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题