gpt4 book ai didi

json - Golang - 使用/遍历 JSON 解析映射

转载 作者:数据小太阳 更新时间:2023-10-29 03:06:57 29 4
gpt4 key购买 nike

使用 PHP 和 JavaScript(以及 Node)解析 JSON 是一项非常简单的操作。从它的外观来看,围棋要复杂得多。考虑以下示例:

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()
}

parseMapA() 调用会返回:

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

但是,parseMapB() 返回:

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

我刚接触 Go 几个小时,所以我想我在这里做错了什么。但是,我不知道那可能是什么。更一般地说,Node 代码的 Go 等价物是什么

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

在围棋?

最佳答案

在 Go 中,解码仅在结构具有导出 字段时才有效,即。以大写字母开头的字段。

将您的第一个结构更改为:

type fileData struct{
Tn string
Size int
}

参见 http://play.golang.org/p/qO3U7ZNrNs举个固定的例子。

此外,如果您打算将此结构编码回 JSON,您会注意到生成的 JSON 使用大写字段,这不是您想要的。

需要添加字段标签:

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

因此 Marshal 函数将使用正确的名称。

关于json - Golang - 使用/遍历 JSON 解析映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30896040/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com