【问题标题】:Extract value from an array in a Json从 Json 中的数组中提取值
【发布时间】:2021-09-16 22:18:46
【问题描述】:

我正在尝试获得“靴子”价值

我的主函数

varjson:=`{
  "identifier": "1",
  "name": "dumbname",
  "person": {
    "items": null,
    "inventory": [
      {
        "T-shirt": "black",
        "Backpack": {
          "BigPocket": {
            "spell": "healing",
            "boots": "speed",
            "shampoo": "Head & Shoulders"
          }
        }
      }
    ],
    "Pockets": null
  }
}`

var res map[string]interface{}

json.Unmarshal([]byte(varjson), &res)

test(res) 

测试功能

    func test(t interface{}) {
      switch reflect.TypeOf(t).Kind() {
       case reflect.Slice:
        s := reflect.ValueOf(t)
    for i := 0; i < s.Len(); i++ {
        fmt.Println(s.Index(i))
        }
      }
    }

但是当我编译时我什么也得不到 如果有另一种方法来获取 Json 中的“启动”值?

【问题讨论】:

标签: json go reflect


【解决方案1】:

假设您可以使用类型,根据您的评论(谢天谢地,完全同意 colm,试图反映结构是粗糙的。​​

一旦你有了一个类型,它就超级容易导航。

特别是fmt.Println(res.Person.Inventory[0].Backpack.BigPocket.Boots) 会给你带来靴子的价值。请记住,Inventory 是一个切片,因此您可能需要对其进行迭代,而在这里我直接访问它,如果 Inventory 为空或有其他元素,这将是不好的。

package main

import (
    "encoding/json"
    "fmt"
)

type AutoGenerated struct {
    Identifier string `json:"identifier"`
    Name       string `json:"name"`
    Person     struct {
        Items     interface{} `json:"items"`
        Inventory []struct {
            TShirt   string `json:"T-shirt"`
            Backpack struct {
                BigPocket struct {
                    Spell   string `json:"spell"`
                    Boots   string `json:"boots"`
                    Shampoo string `json:"shampoo"`
                } `json:"BigPocket"`
            } `json:"Backpack"`
        } `json:"inventory"`
        Pockets interface{} `json:"Pockets"`
    } `json:"person"`
}

func main() {
    varjson := `{
  "identifier": "1",
  "name": "dumbname",
  "person": {
    "items": null,
    "inventory": [
      {
        "T-shirt": "black",
        "Backpack": {
          "BigPocket": {
            "spell": "healing",
            "boots": "speed",
            "shampoo": "Head & Shoulders"
          }
        }
      }
    ],
    "Pockets": null
  }
}`

    var res AutoGenerated
    json.Unmarshal([]byte(varjson), &res)
    
    fmt.Println(res.Person.Inventory[0].Backpack.BigPocket.Boots)
}

在您的原始文件中,问题在于您的 switch 语句只覆盖了一个切片,但初始对象是一个地图。所以你的交换机最初没有找到匹配项

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多