duanshan2988 2015-06-17 15:31
浏览 6
已采纳

Golang-使用/迭代JSON解析地图

With PHP and Javascript (and Node) parsing JSON is a very trivial operation. From the looks of it Go is rather more complicated. Consider the example below

package main

import ("encoding/json";"fmt")

type fileData struct{
 tn string
 size int
}

type jMapA map[string] string
type jMapB map[string] fileData

func parseMapA(){
 var dat jMapA
 s := `{"lang":"Node","compiled":"N","fast":"maybe"}`
 if err := json.Unmarshal([]byte(s), &dat); err != nil {
  panic(err)
 }

 fmt.Println(dat);
 for k,v := range dat{
  fmt.Println(k,v)
 }
}

func parseMapB(){
 var dat jMapB
 s := `{"f1":{"tn":"F1","size":1024},"f2":{"tn":"F2","size":2048}}`
 if err := json.Unmarshal([]byte(s), &dat); err != nil {
  panic(err)
 }

 fmt.Println(dat);
 for k,v := range dat{
  fmt.Println(k,v)
 }
}

func main() {
 parseMapA()
 parseMapB()    
}

The parseMapA() call obligingly returns

map[lang:Node Compiled:N fast:maybe]
lang Node
compiled N
fast maybe

However, parseMapB() returns

map[f1:{ 0}, f2:{ 0}]
f2 { 0}
f1 { 0}

I am into my first few hours with Go so I imagine I am doing something wrong here. However, I have no idea what that might be. I'd much appreciate any help. More generally, what would the Go equivalent of the Node code

for(p in obj){
 doSomethingWith(obj[p]);

}

be in Go?

  • 写回答

1条回答 默认 最新

  • doujiaci7976 2015-06-17 15:36
    关注

    In Go, unmarshaling works only if a struct has exported fields, ie. fields that begin with a capital letter.

    Change your first structure to:

    type fileData struct{
        Tn string
        Size int
    }
    

    See http://play.golang.org/p/qO3U7ZNrNs for a fixed example.

    Moreover, if you intend to marshal this struct back to JSON, you'll notice that the resulting JSON use capitalized fields, which is not what you want.

    You need to add field tags:

    type fileData struct{
        Tn   string `json:"tn"`
        Size int    `json:"size"`
    }
    

    so the Marshal function will use the correct names.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度