json - 如何解码嵌入的json?
问题描述
即使它是嵌套映射并且我提供了映射类型的结构字段,我也无法将 m 解码为值。我不明白为什么?
大多数问题出在结构字段中,我没有将其名称大写,因此它们没有被导出
id int //it should be Id
values map[interface{}]interface{}//should be Values
并且映射键不应该是接口类型,它应该是字符串类型
Values map[interface{}]interface{}
//should be Values map[string]interface{}
文件名与 json 键不匹配,您可以使用struct 标签或将它们与 json 键匹配来解决此问题
//the key for the embedded object was m .
// was trying to decode it into struct
//field and it's name was m .it was like this before fixing it
type edit struct{
Id int
Values [interface{}]interface{}
}
//and json object was like this
{
"id":5,
"m": {"name":"alice"}
}
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
)
type edit struct {
Id int
Values map[string]interface{}
}
func main() {
a := `{
"id":5,
"values":{
"name":"alice"
}
}`
var s edit
dec := json.NewDecoder(strings.NewReader(a))
err := dec.Decode(&s)
if err != nil {
log.Fatal(err)
}
fmt.Println(s)
}
解决方案
您的代码中有几个问题。
edit
首先,必须导出结构的所有字段,这意味着您应该将每个字段的第一个字母大写。
就像下面这样:type edit struct { Id Values }
key
字段的数据类型Values
必须是字符串才能解码json
数据。type edit struct { Id int Values map[string]interface{} }
最后,您的
json
数据"id"
的数据类型错误。它必须int
与您的Go
结构相匹配。此外,您的结构中没有"m"
定义。"m"
必须替换为"values"
以匹配您的结构Go
。就像下面这样{ "id": 5, "values":{ "name": "alice" } }
只是为了让您知道,您可以简单地使用以下代码将json
数据解组到Go
结构中。
err := json.Unmarshal([]byte(a), &s)
推荐阅读
- rust - 像 Netcat 一样的 Rust UDP 监听器
- python - 使用python进行网页抓取,request.json()显示status_code为200但无法提取json数据
- python - Python Django TypeError:“模块”对象不可调用
- python - 检查列表是否包含任何字典键
- excel - 在 Excel 中为 .txt 路径指定新文件夹
- mysql - mysql按优先级顺序获取记录,无需全文搜索
- react-native - 错误:找不到模块'source-map-support'
- html - 在 HTML 中显示 YAML(Trello 风格的卡片)
- javascript - 为什么当我单击取消按钮时它仍然调用表单事件处理程序?
- android - 如何在 Android Studio Java 中将 JSON 数组显示到表格视图或布局中