json - 创建动态json

标签 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_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)
}

如何将set添加到location并添加到domain以创建嵌套结构,因为map只能具有一个类型字符串或嵌套结构?

最佳答案

也许我在这里有点遗漏了一点,但是我不明白为什么这是如此动态,以致于无法通过struct和json unmarshal方法来处理。

请参阅以下示例

https://play.golang.org/p/8nrO36HQGhy

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

关于json - 创建动态json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58671566/

相关文章:

asp.net - json字符串从vb.net端到asp.net

javascript - 尝试访问 json 内容并以网格方式显示

javascript - 无法从 json 记录集中打印表中的变量

sql - 像 python 风格一样获取行

go - 安装 Go 依赖失败

ajax - 如何在 GAE GO 中实现 AJAX

go - 发送蓝牙广告包并获得一些答案

json - 如何在 MongoDB 中获得彩色查询输出和 shell?

javascript - 如何在 JavaScript 中使用其函数之外的值?

mongodb - Golang mongodb 驱动程序错误模式验证