简体   繁体   English

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

[英]How to unmarshal nested json to a struct, if the outer element is not the same in GO

Hi i wonder if it is possible to unmarshal this given json to a struct 嗨,我想知道是否有可能将给定的json解组到结构

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

Here is an example of the json 这是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 任何帮助都很好,谢谢

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. 考虑到它的动态性质,使用map [string]接口可能会更容易,因为您将无法定义诸如asd123和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. 最好的方法是更好地组织json数据,使其更好地适合结构,否则使用反射。 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. 无需进行更多工作,我将使用上面的for循环,并以对我来说有意义的方式将其添加到结构中,以便可以更轻松地访问数据。 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. 考虑JSON解析器的开始,因此现在您可以访问json数据,将其放入一个结构中,然后更改数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM