duanci1939 2018-01-23 22:10
浏览 88
已采纳

Golang使用具有动态相关键的json

I am new to GO and I am trying to consume json data from a variety of API's using GO and place them in struct's one of them Formats the data like so

{"MS": {
   "last":"25",
"highestBid":"20"},
"GE": {        
    "last": "24",        
    "highestBid": "22"}
}

While I can find information on Consuming with dynamic keys, all the examples I found throw away the Outer most key as arbitrary and irrelevant. I need to use it as a key value pair like bellow:

{"MarketName": "GE", "last":"24","higestBid":"22"}

I understand Using Interface map but I cant figure out how to map the dynamic key to the struct as a key : value pair like above. My Code example to map leaving out the need key can be found at play ground Relevant Code

  package main

import (
    "encoding/json"
    "fmt"

)

var jsonBytes = []byte(`
    {"MS": {
       "last":"25",
    "highestBid":"20"},
    "GE": {        
        "last": "24",        
        "highestBid": "22"}
    }`)

type Market struct {
    Last       string 
    HighestBid string 
}

func main() {
    // Unmarshal using a generic interface
    var f interface{}
    err := json.Unmarshal(jsonBytes, &f)
    if err != nil {
        fmt.Println("Error parsing JSON: ", err)
    }
    fmt.Println(f)



}

as it stands it outputs

map[MS:map[last:25 highestBid:20] GE:map[highestBid:22 last:24]]

As I stated I am new to GO and as much help and explanation that i can get would be very appreciated

  • 写回答

2条回答 默认 最新

  • doulian7252 2018-01-23 22:15
    关注

    You're halfway there already, you just need to unmarshal into your struct and then massage the data a little:

    type Market struct {
        Name string
        Last       string 
        HighestBid string 
    }
    
    func main() {
        // Unmarshal using a generic interface
        var f map[string]Market
        err := json.Unmarshal(jsonBytes, &f)
        if err != nil {
            fmt.Println("Error parsing JSON: ", err)
            return
        }
        markets := make([]Market, 0, len(f))
        for k,v := range f {
            v.Name = k
            markets = append(markets,v)
        }
        fmt.Println(markets)
    }
    

    Working example here: https://play.golang.org/p/iagx8RWFfx_k

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?