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.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部