How can I convert this JSON string into a struct?

huangapple go评论66阅读模式
英文:

How can I convert this JSON string into a struct?

问题

你好!要将这个JSON字符串分成两个不同的数组,你可以按照以下步骤进行操作:

  1. 首先,你需要将JSON字符串解析为一个对象。你可以使用一个JSON解析库,比如encoding/json包来完成这个任务。例如,你可以使用json.Unmarshal()函数将JSON字符串解析为一个结构体对象。

  2. 解析后的结构体对象将包含lastUpdateIdbidsasks字段。你可以通过访问这些字段来获取对应的数组。

  3. 根据你的需求,你可以将bidsasks字段分别存储到两个不同的数组中。

下面是一个示例代码,演示了如何将JSON字符串解析为两个不同的数组:

import (
    "encoding/json"
    "fmt"
)

type Response struct {
    LastUpdateId int64       `json:"lastUpdateId"`
    Bids         [][]string  `json:"bids"`
    Asks         [][]string  `json:"asks"`
}

func main() {
    jsonString := `{
        "lastUpdateId": 6219028865,
        "bids": [
            ["45529.93000000", "0.59554000"],
            ["45529.92000000", "0.04402000"]
        ],
        "asks": [
            ["45529.94000000", "3.77220000"],
            ["45529.95000000", "0.07800000"]
        ]
    }`

    var response Response
    err := json.Unmarshal([]byte(jsonString), &response)
    if err != nil {
        fmt.Println("JSON解析错误:", err)
        return
    }

    bids := response.Bids
    asks := response.Asks

    fmt.Println("Bids数组:", bids)
    fmt.Println("Asks数组:", asks)
}

你可以根据自己的需求进一步处理这两个数组。希望对你有帮助!

英文:

How can I this JSON string into two distinct arrays? I want a bids array and an asks array, however, I am unsure. This is the JSON:

{

   "lastUpdateId":6219028865,
   "bids":[
         "45529.93000000",
         "0.59554000"
      ],
      [
         "45529.92000000",
         "0.04402000"
      ],
   ],
   "asks":[
      [
         "45529.94000000",
         "3.77220000"
      ],
      [
         "45529.95000000",
         "0.07800000"
      ],
   ]
}

I recieve the JSON from the request:

b, err := ioutil.ReadAll(resp.Body)

How would I go about this process?

答案1

得分: 3

type Output struct {
    LastUpdateId int64
    Bids         [][]string
    Asks         [][]string
}

// ...

var out Output
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
    panic(err)
}

fmt.Println(out.Bids)
fmt.Println(out.Asks)
类型 Output struct {
    LastUpdateId int64
    Bids         [][]string
    Asks         [][]string
}

// ...

var out Output
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
    panic(err)
}

fmt.Println(out.Bids)
fmt.Println(out.Asks)
英文:
type Output struct {
    LastUpdateId int64
    Bids         [][]string
    Asks         [][]string
}

// ...

var out Output
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
    panic(err)
}

fmt.Println(out.Bids)
fmt.Println(out.Asks)

huangapple
  • 本文由 发表于 2021年9月11日 21:37:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/69143530.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定