json - 在 Go 中获取内部 JSON 值

标签 json go

一个简单的问题,我在如何构建用于 JSON 解码的结构时遇到困难。

如何将结构的内部字段复制到结构的另一个字段?

我有 JSON

{
    "Trains": [{
        "Car": "6",
        "Destination": "SilvrSpg",
        "DestinationCode": "B08",
        "DestinationName": "Silver Spring",
        "Group": "1",
        "Line": "RD",
        "LocationCode": "A13",
        "LocationName": "Twinbrook",
        "Min": "1"
    }]
}

我有结构

type Trains struct {
  Min      string `json:"Min"`
  DestName string `json:"DestinationName"`
  DestCode string `json:"DestinationCode"`
  LocName  string `json:"LocationName"`
  LocCode  string `json:"LocationCode"`
  Line     string `json:"Line"`
}

type AllData struct {
  Data []Trains `json:"Trains"`
}

如何将 Trains.LocationCode 的值获取到类似这样的结构

type AllData struct {
  Id Trains[0].LocCode value
  Data []Trains `json:"Trains"`
}

所以我基本上只需要像这样的 JSON

{
    "Id":"A13",
    "Data": [{
        "Car": "6",
        "Destination": "SilvrSpg",
        "DestinationCode": "B08",
        "DestinationName": "Silver Spring",
        "Group": "1",
        "Line": "RD",
        "LocationCode": "A13",
        "LocationName": "Twinbrook",
        "Min": "1"
    }]
}

Id 是 Trains 结构的内部值。

我如何构造一个结构来反射(reflect)这一点?

最佳答案

JSON 解码器没有这个能力。您必须在您的应用程序中编写这行代码。

package main

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

var s = `
{
    "Trains": [{
        "Car": "6",
        "Destination": "SilvrSpg",
        "DestinationCode": "B08",
        "DestinationName": "Silver Spring",
        "Group": "1",
        "Line": "RD",
        "LocationCode": "A13",
        "LocationName": "Twinbrook",
        "Min": "1"
    }]
}`

type Train struct {
    Min      string `json:"Min"`
    DestName string `json:"DestinationName"`
    DestCode string `json:"DestinationCode"`
    LocName  string `json:"LocationName"`
    LocCode  string `json:"LocationCode"`
    Line     string `json:"Line"`
}

type Data struct {
    // The name "-" tells the JSON decoder to ignore this field.
    ID     string `json:"-"`
    Trains []Train
}

func main() {
    var d Data
    if err := json.Unmarshal([]byte(s), &d); err != nil {
        log.Fatal(err)
    }
    if len(d.Trains) < 1 {
        log.Fatal("No trains")
    }
    // Copy value from inner to outer.
    d.ID = d.Trains[0].LocCode
    fmt.Printf("%+v\n", &d)
}

关于json - 在 Go 中获取内部 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25894352/

相关文章:

python - 在 Python 中循环遍历 JSON 数组

java - 来自不同调度作业的同一列版本

string - 你能用相同的值设置多个(不同的)标签吗?

go - else 之前意外的分号或换行符,即使 else 之前都没有 if

go - 如何通过 Golang 中的短变量声明将返回值分配给函数输入?

golang 模板不适用于 httprouter

c# - 读取 json 文件异常 "Unhandled Exception: System.TypeInitializationException: The type initializer for "

PHP JSON 数据到 Xcode Swift 数组

javascript - Google Places API Web 服务服务器端解决方案

go - Apache Beam - 使用 Go SDK 进行 API 调用的批处理元素?