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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题