douzhan1994 2017-03-28 18:21
浏览 34
已采纳

如果外部元素在GO中不相同,如何将嵌套的json解组到结构

Hi i wonder if it is possible to unmarshal this given json to a struct

type Movie struct {
    Title string
    Actors []string
    ID int
    Length int
    RelaseDate string
}

Here is an example of the json

{
"movies": [
    {
        "movie_title_A": {
            "actors": [
                "<actorID1123123>",
                "<actorID1123123>",
                "<actorID1123123>",
                "<actorID1123123>",
                "<actorID1123123>",
                "<actorID1123123>...."
            ]
        },
        "ID": 99992,
        "length": 120,
        "relaseDate": "2.10.2012"
    },
    {
        "movie_title_B": {
            "actors": [
                "<actorID1123123>",
                "<actorID1123123>",
                "<actorID1123123>",
                "<actorID1123123>",
                "<actorID1123123>",
                "<actorID1123123>...."
            ]
        },
        "ID": 123124,
        "length": 90,
        "relaseDate": "10.10.2012"
    }
]
}

As you can see the Name field can take on any name, since it is the title of the movie. Is there an efficient way to put it into the struct above? Any help would be nice, thanks

  • 写回答

1条回答 默认 最新

  • douzhu6149 2017-03-28 18:57
    关注

    given it's dynamic nature it might be easier use a map[string]interface as you'll not be able to define dynamic keys like asd123 and 2movie23123.

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    const j = `{
        "movies": [
            {
                "asd123": {
                    "actors": [
                        "<actorID1123123>",
                        "<actorID1123123>",
                        "<actorID1123123>",
                        "<actorID1123123>",
                        "<actorID1123123>",
                        "<actorID1123123>"
                    ]
                },
                "ID": 99992,
                "length": 120,
                "relaseDate": "2.10.2012"
            },
            {
                "2movie23123": {
                    "actors": [
                        "<actorID1123123>",
                        "<actorID1123123>",
                        "<actorID1123123>",
                        "<actorID1123123>",
                        "<actorID1123123>",
                        "<actorID1123123>"
                    ]
                },
                "ID": 123124,
                "length": 90,
                "relaseDate": "10.10.2012"
            }
        ]
        }`
    
    // Movies ...
    type Movies struct {
        Name        string
        ID          float64
        Length      float64
        ReleaseDate string
        Actors      []interface{}
    }
    
    func main() {
        data := map[string]interface{}{}
        err := json.Unmarshal([]byte(j), &data)
        if err != nil {
            panic(err)
        }
        // printing it out to show you it marshaled
        // b, _ := json.MarshalIndent(data, "", " ")
        // fmt.Println(string(b))
        //
        var myMovies []Movies
    
        for _, d := range data {
            temp := Movies{}
            converting := d.([]interface{})
            for _, movie := range converting {
                convertingMovie := movie.(map[string]interface{})
                temp.Length = convertingMovie["length"].(float64)
                temp.ID = convertingMovie["ID"].(float64)
                temp.ReleaseDate = convertingMovie["relaseDate"].(string)
                // getting rid of these keys so the for loop below doesn't iterate on them
                // need the for loop cuz I don't know what the key name is
                delete(convertingMovie, "length")
                delete(convertingMovie, "ID")
                delete(convertingMovie, "relaseDate")
                for key, val := range convertingMovie {
                    temp.Name = key
                    actors := val.(map[string]interface{})
                    temp.Actors = actors["actors"].([]interface{})
                }
            }
            myMovies = append(myMovies, temp)
        }
    
        b, _ := json.MarshalIndent(myMovies, "", " ")
        fmt.Println(string(b))
    
    }
    

    Probably a better way to do it above, but I provided a quick example. The best way would be to organize the json data better so that it fits into a struct better, otherwise the use reflection. Without to much more work, I'd use the for loop above, and add it to a struct in a may that makes sense to me and so that it can access the data easier. Consider above the start of the JSON parser, so now that you can access the json data, fit it into a struct then, change data around.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探