dquv73115 2016-04-01 07:43
浏览 63
已采纳

将JSON解组为嵌套结构

I have different json byte inputs that I need to unmarshal into a nested json structure. I am able to unmarshal the json into the struct App. However I am unable to add to "status" struct.

I tried to unmarshal, but that doesnt work since my app1 & app2 are of type App instead of bytes. And trying to set directly gives the error "cannot use app1 (type App) as type []App in assignment"

package main

import (
    "encoding/json"
    "fmt"
    "reflect"
)

type App struct {
    Appname string `json:"appname"`
    Builds  string `json:"builds"`
}

type Status struct {
    Apps []App `json:"apps"`
}

func main() {
    jsonData1 := []byte(`
            {  
               "appname": "php1",
               "buildconfigs":"deleted"
            }
        `)

    jsonData2 := []byte(`
            {  
               "appname": "php2",
               "buildconfigs":"exists"
            }
        `)

    // unmarshal json data to App
    var app1 App
    json.Unmarshal(jsonData1, &app1)

    var app2 App
    json.Unmarshal(jsonData2, &app2)

    var status Status
    //json.Unmarshal(app1, &status)
    //json.Unmarshal(app2, &status)

    status.Apps = app1
    status.Apps = app2

    fmt.Println(reflect.TypeOf(app1))
    fmt.Println(reflect.TypeOf(app1))
}
  • 写回答

2条回答 默认 最新

  • dousao6313 2016-04-01 08:22
    关注

    You can't assign single element to array field so convert your

    status.Apps = app1
    status.Apps = app2
    

    to something like

    status.Apps = []App{app1, app2}
    

    or

    status.Apps = []App{}
    status.Apps = append(status.Apps, app1)
    status.Apps = append(status.Apps, app2)
    

    Also your JSON field named buildconfigs and in struct specification json:"builds". Structure's field always will be empty in this case.

    Working example http://play.golang.org/p/fQ-XQsgK3j

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度