创建动态json
我需要创建动态json,即其键值不同,下面提到的是json创建动态json,json,go,Json,Go,我需要创建动态json,即其键值不同,下面提到的是json [{"email":"xxx@gmail.com","location":{"set":"Redmond"},"fname":{"set":"xxxxx"},"clicked_time":{"set":"zz"},"domain":{"add":"ttt"}},{"email":"zzz@gmail.com","location":{"set":"Greece"},"fname":{"set":"zzzzz"},"clicked_tim
[{"email":"xxx@gmail.com","location":{"set":"Redmond"},"fname":{"set":"xxxxx"},"clicked_time":{"set":"zz"},"domain":{"add":"ttt"}},{"email":"zzz@gmail.com","location":{"set":"Greece"},"fname":{"set":"zzzzz"},"clicked_time":{"set":"zzz"},"domain":{"add":"zxxxx"}}]
我尝试使用以下代码:
rows := []map[string]string{}
if i > 0 {
row := make(map[string]string)
for j:=0;j<len(record);j++ {
key := header[j]
value := record[j]
row[key] = value
}
rows = append(rows, row)
}
行:=[]映射[字符串]字符串{}
如果i>0{
行:=生成(映射[字符串]字符串)
对于j:=0;j也许我在这里有点忽略了这一点,但我不明白为什么这是如此动态,以至于无法用结构和json unmarshal方法来处理
请参见下面的示例
制作一个类型为map[string]interface{}
的映射,谢谢,你能给我一些示例的实现吗,因为我刚开始工作。
package main
import (
"encoding/json"
"fmt"
)
type (
Details struct {
Email string `json:"email"`
Location Entry `json:"location"`
FName Entry `json:"fname"`
ClickedTime Entry `json:"clicked_time"`
Domain Entry `json:"domain"`
}
Entry struct {
Set string `json:"set"`
Add string `json:"add"`
}
)
func main() {
d := []byte(`[{
"email": "xxx@gmail.com",
"location": {
"set": "Redmond"
},
"fname": {
"set": "xxxxx"
},
"clicked_time": {
"set": "zz"
},
"domain": {
"add": "ttt"
}
}, {
"email": "zzz@gmail.com",
"location": {
"set": "Greece"
},
"fname": {
"set": "zzzzz"
},
"clicked_time": {
"set": "zzz"
},
"domain": {
"add": "zxxxx"
}
}]`)
x := []Details{}
_ = json.Unmarshal(d, &x)
fmt.Printf("%+v\n", x)
}