gpt4 book ai didi

json - 在不使用结构的情况下将 json 转换为 map slice 并将 map slice 转换为 json

转载 作者:IT王子 更新时间:2023-10-29 02:34:26 26 4
gpt4 key购买 nike

我正在尝试将 json 字符串从 http 请求转换为一片 map 。而且我还应该将一片 map/s 转换为 json 字符串以用于 http 响应。

在以下两种情况下,我想将以下内容转换为一片 map 。来自http请求的json字符串可能是几个相同键值json对象的数组,比如;

[
{ title: 'JavaScript: The Good Parts', author: 'Douglas Crockford',
releaseDate: '2008', keywords: 'JavaScript Programming' },
{ title: 'The Little Book on CoffeeScript', author: 'Alex MacCaw',
releaseDate: '2012', keywords: 'CoffeeScript Programming' },
{ title: 'Scala for the Impatient', author: 'Cay S. Horstmann',
releaseDate: '2012', keywords: 'Scala Programming' },
{ title: 'American Psycho', author: 'Bret Easton Ellis',
releaseDate: '1991', keywords: 'Novel Splatter' },
{ title: 'Eloquent JavaScript', author: 'Marijn Haverbeke',
releaseDate: '2011', keywords: 'JavaScript Programming' }
]

或者像这样的一个;

{ title: 'Eloquent JavaScript', author: 'Marijn Haverbeke',
releaseDate: '2011', keywords: 'JavaScript Programming' }

第二个任务是将 map/s slice 转换为 json 字符串。

然而,我无法在这两个过程中取得成功。

json 包可以为结构完成这两项任务,我知道这一点。

出于设计考虑,我不应该使用预先编码的结构。

在 Go 中是否有已知的方法来执行这些操作。

最佳答案

您确实可以使用 map[string]interface{} 并且可以与 { "title": ....., "keywords": ["CoffeeScript", “编程”] }就好了

你必须使用类似的东西:

for i := 0; i < len(b); i++ {
fmt.Printf("%s by %s was release at %s\n", b[i]["title"], b[i]["author"])
switch v := b[i]["keywords"].(type) {
case []interface{}:
for i := 0; i < len(v); i++ {
switch v := v[i].(type) {
case string:
fmt.Println("\tstring in a slice", v)
case float64: //numbers in json are float64 by default
fmt.Println("\tnumber in a slice", v)
default:
fmt.Printf("\tunknown type (%T)", v, v)
}
}
case string:
fmt.Println("\tstring", v)
}
}

playground

关于json - 在不使用结构的情况下将 json 转换为 map slice 并将 map slice 转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25583281/

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