doupao3662 2015-07-30 12:02
浏览 37
已采纳

如何将具有相同内部结构的两个json解组为一个单独的golang结构?

I have two json files with following structure

{
 "cast": [
        {
            "url": "carey-mulligan",
            "name": "Carey Mulligan",
            "role": "Actress"
        },
        {
            "url": "leonardo-dicaprio",
            "name": "Leonardo DiCaprio",
            "role": "Actor"
        },
        .
        .
        .
         ]
}

and

{
 "movie": [
        {
            "url": "carey-mulligan",
            "name": "Carey Mulligan",
            "role": "Actress"
        },
        {
            "url": "leonardo-dicaprio",
            "name": "Leonardo DiCaprio",
            "role": "Actor"
        },
        .
        .
        .
         ]
}

as you can see internal structure of the json is same for cast and movie. I want to unmarshel these json file into the same golang structure. But i am not able to give two name tags (cast and movie) for same struct element. I want something like

type Detail struct {
    Name string `json:"name"`
    Url  string `json:"url"`
    Role string `json:"role"`
}

type Info struct {
    Detail []Detail `json:"cast or movie"`
}

In which case Detail could parse both cast and movie.

Here is my current code

// RIMAGE project main.go
package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

const (
    website = "https://data.moviebuff.com/"
)

func main() {
    fmt.Println("Hello World!")
    content, err := ioutil.ReadFile("data/great-getsby")
    if err != nil {
        panic(err)
    }

    var info Info

    err = json.Unmarshal(content, &info)
    if err != nil {
        panic(err)
    }

    fmt.Println(info.Detail)
}

type Detail struct {
    Name string `json:"name"`
    Url  string `json:"url"`
    Role string `json:"role"`
}

type Info struct {
    Detail []Detail `json:"cast" json:"movie"
}

but it only works for first tag "cast" and gives nill in case json contain the movie.

Thanks in advance.

  • 写回答

3条回答 默认 最新

  • dongle19863 2015-07-30 12:48
    关注

    You can use type Info map[string][]Detail instead of your struct. Try it on the <kbd>Go playground</kbd>

    Or you can use both types in your structure, and make method Details() which will return right one:

    type Info struct {
        CastDetails  []Detail `json:"cast"`
        MovieDetails []Detail `json:"movie"`
    }
    
    func (i Info) Details() []Detail {
        if i.CastDetails == nil {
            return i.MovieDetails
        }
        return i.CastDetails
    }
    

    Try it on the <kbd>Go playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)