json - 在 Go 中如何动态解析 JSON?
问题描述
所以我在 Go 中解析 JSON 文件时遇到了一些问题。我已经尝试了很多如何解决的方法,但我似乎没有找到解决方案。
所以假设我有一些看起来像这样的 JSON 文件
{
"products": [
{
"id": 201,
"name": "Nulla",
"price": 207,
"categoryId": 1,
"rate": 2.44,
"content": "Culpa sed tenetur incidunt quia veniam sed molliti",
"review": 78,
"imageUrl": "https://dummyimage.com/400x350"
},
{
"id": 202,
"name": "Corporis",
"price": 271,
"categoryId": 1,
"rate": 2.18,
"content": "Nam incidunt blanditiis odio inventore. Nobis volu",
"review": 67,
"imageUrl": "https://dummyimage.com/931x785"
},
{
"id": 203,
"name": "Minus",
"price": 295,
"categoryId": 1,
"rate": 0.91,
"content": "Quod reiciendis aspernatur ipsum cum debitis. Quis",
"review": 116,
"imageUrl": "https://dummyimage.com/556x985"
}
]
}
我想动态解析它(不为它制作结构)。我已经尝试过,map[string]interface{}
但它不起作用。我已经尝试了另一个名为 jsoniter 的第三方库,但它也不起作用。
我可以让它“以某种方式”工作的唯一方法是尝试用括号包裹 json_string
[jsonstring]
这是我的代码。
file, _ := ioutil.ReadFile("p1.json")
var results []map[string]interface{}
json.Unmarshal(file, &results)
fmt.Printf("%+v", results) // Output []
解决方案
始终检查错误。从您检查错误json.Unmarshal
可以看到:
2009/11/10 23:00:00 json: cannot unmarshal object into Go value of type []map[string]interface {}
您正在使用一片地图[]map[string]interface{}
来编组,而不是您想要的地图:
// var results []map[string]interface{} // bad-type
var results map[string]interface{} // correct-type
err := json.Unmarshal(body, &results)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", results) // Output [map[categoryId:1 content:Culpa sed tenetur incidunt quia veniam sed molliti id:20 ...
推荐阅读
- javascript - Javascript代码有效,但不是立即
- jenkins - Jenkins JUnit 在 XML 文件中找不到结果
- python - 等效于 Python 的 JProfiler
- python - 生成器和过滤器的 PYTHON 分配
- java - 何时使用多对一和单对多与多对多
- c++ - 避免需要使用 operator= 指定
- javascript - 使用 puppeteer 返回具有相同选择器的 div 列表
- python - 我正在构建一个烧瓶网站,但出现错误:sqlalchemy.exc.NoForeignKeysError
- react-native - 如何在本机反应中使用 setTimeout?
- python - 如何从需要密码的网站上抓取文本数据