当前位置: 首页 > 知识库问答 >
问题:

Golang使用未知密钥解析JSON〔重复〕

晋功
2023-03-14

我正在尝试用动态字段键将json解组到json从storcli utility for linux返回的结构。一部分代码运行良好,但是如果json数据包含许多结构,我就不能解组它。我认为这是因为DriveDetailedInformation结构没有所有的json标签。有人能帮我吗?

package main

import (
    "fmt"
    "encoding/json"
)

type jsonStruct struct {
    Controllers []struct {
        CommandStatus struct {
            Controller  int    `json:"Controller"`
            Status      string `json:"Status"`
            Description string `json:"Description"`
        } `json:"Command Status"`
        ResponseData map[string]*json.RawMessage `json:"Response Data"`
    } `json:"Controllers"`
}

type DriveStruct struct {
    EIDSlt string `json:"EID:Slt"`
    DID    int    `json:"DID"`
    State  string `json:"State"`
    DG     int    `json:"DG"`
    Size   string `json:"Size"`
    Intf   string `json:"Intf"`
    Med    string `json:"Med"`
    SED    string `json:"SED"`
    PI     string `json:"PI"`
    SeSz   string `json:"SeSz"`
    Model  string `json:"Model"`
    Sp     string `json:"Sp"`
}

type DriveDetailedInformation struct {
    DriveState            map[string]DriveStateStruct
    DriveDeviceAttributes map[string]DriveDeviceAttributesStruct
    DrivePoliciesSettings map[string]DrivePoliciesSettingsStruct
    InquiryData           string `json:"Inquiry Data"`
}

type DriveStateStruct struct {
    ShieldCounter            int    `json:"Shield Counter"`
    MediaErrorCount          int    `json:"Media Error Count"`
    OtherErrorCount          int    `json:"Other Error Count"`
    BBMErrorCount            int    `json:"BBM Error Count"`
    DriveTemperature         string `json:"Drive Temperature"`
    PredictiveFailureCount   int    `json:"Predictive Failure Count"`
    SMARTAlertFlaggedByDrive string `json:"S.M.A.R.T alert flagged by drive"`
}

type DriveDeviceAttributesStruct struct {
    SN               string `json:"SN"`
    ManufacturerID   string `json:"Manufacturer Id"`
    ModelNumber      string `json:"Model Number"`
    NANDVendor       string `json:"NAND Vendor"`
    WWN              string `json:"WWN"`
    FirmwareRevision string `json:"Firmware Revision"`
    RawSize          string `json:"Raw size"`
    CoercedSize      string `json:"Coerced size"`
    NonCoercedSize   string `json:"Non Coerced size"`
    DeviceSpeed      string `json:"Device Speed"`
    LinkSpeed        string `json:"Link Speed"`
    NCQSetting       string `json:"NCQ setting"`
    WriteCache       string `json:"Write cache"`
    SectorSize       string `json:"Sector Size"`
    ConnectorName    string `json:"Connector Name"`
}

type DrivePoliciesSettingsStruct struct {
    DrivePosition                            string `json:"Drive position"`
    EnclosurePosition                        int    `json:"Enclosure position"`
    ConnectedPortNumber                      string `json:"Connected Port Number"`
    SequenceNumber                           int    `json:"Sequence Number"`
    CommissionedSpare                        string `json:"Commissioned Spare"`
    EmergencySpare                           string `json:"Emergency Spare"`
    LastPredictiveFailureEventSequenceNumber int    `json:"Last Predictive Failure Event Sequence Number"`
    SuccessfulDiagnosticsCompletionOn        string `json:"Successful diagnostics completion on"`
    SEDCapable                               string `json:"SED Capable"`
    SEDEnabled                               string `json:"SED Enabled"`
    Secured                                  string `json:"Secured"`
    Locked                                   string `json:"Locked"`
    NeedsEKMAttention                        string `json:"Needs EKM Attention"`
    PIEligible                               string `json:"PI Eligible"`
    Certified                                string `json:"Certified"`
    WidePortCapable                          string `json:"Wide Port Capable"`
    PortInformation                          []struct {
        Port       int    `json:"Port"`
        Status     string `json:"Status"`
        Linkspeed  string `json:"Linkspeed"`
        SASAddress string `json:"SAS address"`
    } `json:"Port Information"`
}

var jsonData = `
{
   "Controllers":[
      {
         "Command Status":{
            "Controller":0,
            "Status":"Success",
            "Description":"Show Drive Information Succeeded."
         },
         "Response Data":{
            "Drive /c0/e31/s0":[
               {
                  "EID:Slt":"31:0",
                  "DID":19,
                  "State":"Onln",
                  "DG":0,
                  "Size":"9.094 TB",
                  "Intf":"SATA",
                  "Med":"HDD",
                  "SED":"N",
                  "PI":"N",
                  "SeSz":"512B",
                  "Model":"ST10000DM0004-1ZC101",
                  "Sp":"U"
               }
            ],
            "Drive /c0/e31/s0 - Detailed Information":{
               "Drive /c0/e31/s0 State":{
                  "Shield Counter":0,
                  "Media Error Count":0,
                  "Other Error Count":0,
                  "BBM Error Count":0,
                  "Drive Temperature":" 25C (77.00 F)",
                  "Predictive Failure Count":0,
                  "S.M.A.R.T alert flagged by drive":"No"
               },
               "Drive /c0/e31/s0 Device attributes":{
                  "SN":"            ZA23V0DH",
                  "Manufacturer Id":"ATA     ",
                  "Model Number":"ST10000DM0004-1ZC101",
                  "NAND Vendor":"NA",
                  "WWN":"5000c500a5ad06b6",
                  "Firmware Revision":"DN01    ",
                  "Raw size":"9.095 TB [0x48c400000 Sectors]",
                  "Coerced size":"9.094 TB [0x48c300000 Sectors]",
                  "Non Coerced size":"9.094 TB [0x48c300000 Sectors]",
                  "Device Speed":"6.0Gb/s",
                  "Link Speed":"6.0Gb/s",
                  "NCQ setting":"N/A",
                  "Write cache":"N/A",
                  "Sector Size":"512B",
                  "Connector Name":""
               },
               "Drive /c0/e31/s0 Policies/Settings":{
                  "Drive position":"DriveGroup:0, Span:0, Row:0",
                  "Enclosure position":0,
                  "Connected Port Number":"0(path0) ",
                  "Sequence Number":2,
                  "Commissioned Spare":"No",
                  "Emergency Spare":"No",
                  "Last Predictive Failure Event Sequence Number":0,
                  "Successful diagnostics completion on":"N/A",
                  "SED Capable":"No",
                  "SED Enabled":"No",
                  "Secured":"No",
                  "Locked":"No",
                  "Needs EKM Attention":"No",
                  "PI Eligible":"No",
                  "Certified":"No",
                  "Wide Port Capable":"No",
                  "Port Information":[
                     {
                        "Port":0,
                        "Status":"Active",
                        "Linkspeed":"6.0Gb/s",
                        "SAS address":"0x5003048001927c6c"
                     }
                  ]
               },
               "Inquiry Data":""
            },
            "Drive /c0/e31/s1":[
               {
                  "EID:Slt":"31:1",
                  "DID":20,
                  "State":"Onln",
                  "DG":0,
                  "Size":"9.094 TB",
                  "Intf":"SATA",
                  "Med":"HDD",
                  "SED":"N",
                  "PI":"N",
                  "SeSz":"512B",
                  "Model":"ST10000DM0004-1ZC101",
                  "Sp":"U"
               }
            ],
            "Drive /c0/e31/s1 - Detailed Information":{
               "Drive /c0/e31/s1 State":{
                  "Shield Counter":0,
                  "Media Error Count":0,
                  "Other Error Count":0,
                  "BBM Error Count":0,
                  "Drive Temperature":" 25C (77.00 F)",
                  "Predictive Failure Count":0,
                  "S.M.A.R.T alert flagged by drive":"No"
               },
               "Drive /c0/e31/s1 Device attributes":{
                  "SN":"            ZA23MCVS",
                  "Manufacturer Id":"ATA     ",
                  "Model Number":"ST10000DM0004-1ZC101",
                  "NAND Vendor":"NA",
                  "WWN":"5000c500a5acc582",
                  "Firmware Revision":"DN01    ",
                  "Raw size":"9.095 TB [0x48c400000 Sectors]",
                  "Coerced size":"9.094 TB [0x48c300000 Sectors]",
                  "Non Coerced size":"9.094 TB [0x48c300000 Sectors]",
                  "Device Speed":"6.0Gb/s",
                  "Link Speed":"6.0Gb/s",
                  "NCQ setting":"N/A",
                  "Write cache":"N/A",
                  "Sector Size":"512B",
                  "Connector Name":""
               },
               "Drive /c0/e31/s1 Policies/Settings":{
                  "Drive position":"DriveGroup:0, Span:0, Row:1",
                  "Enclosure position":0,
                  "Connected Port Number":"0(path0) ",
                  "Sequence Number":2,
                  "Commissioned Spare":"No",
                  "Emergency Spare":"No",
                  "Last Predictive Failure Event Sequence Number":0,
                  "Successful diagnostics completion on":"N/A",
                  "SED Capable":"No",
                  "SED Enabled":"No",
                  "Secured":"No",
                  "Locked":"No",
                  "Needs EKM Attention":"No",
                  "PI Eligible":"No",
                  "Certified":"No",
                  "Wide Port Capable":"No",
                  "Port Information":[
                     {
                        "Port":0,
                        "Status":"Active",
                        "Linkspeed":"6.0Gb/s",
                        "SAS address":"0x5003048001927c6d"
                     }
                  ]
               },
               "Inquiry Data":""
            }
         }
      }
   ]
}
`

func main() {
    var f jsonStruct
    err := json.Unmarshal([]byte(jsonData), &f)
    if err != nil {
        fmt.Println("Error parsing JSON: ", err)
    }

    for _, controller := range f.Controllers {
        for k, v := range controller.ResponseData {

            ///THAT IS WORK
            var ds []DriveStruct
            if err := json.Unmarshal(*v, &ds); err == nil {
                fmt.Println(k, ds)

            }

            ///THAT IS NOT WORK WHY?
            var dds DriveDetailedInformation
            if err := json.Unmarshal(*v, &dds); err == nil {
                fmt.Println(k, dds)
            }
        }
    }
}

共有1个答案

公孙志
2023-03-14

因为你的键值不正确。下面是我修改的代码。

type DriveDetailedInformation struct {
DriveState            DriveStateStruct `json:"Drive /c0/e31/s0 State"`
DriveDeviceAttributes DriveDeviceAttributesStruct `json:"Drive /c0/e31/s0 Device attributes"`
DrivePoliciesSettings DrivePoliciesSettingsStruct `json:"Drive /c0/e31/s0 Policies/Settings"`
InquiryData           string `json:"Inquiry Data"`
}

type DriveDetailedInformation1 struct {
    DriveState            DriveStateStruct `json:"Drive /c0/e31/s1 State"`
    DriveDeviceAttributes DriveDeviceAttributesStruct `json:"Drive /c0/e31/s1 Device attributes"`
    DrivePoliciesSettings DrivePoliciesSettingsStruct `json:"Drive /c0/e31/s1 Policies/Settings"`
    InquiryData           string `json:"Inquiry Data"`
}
func main() {
    var f jsonStruct
    err := json.Unmarshal([]byte(jsonData), &f)
    if err != nil {
        fmt.Println("Error parsing JSON: ", err)
    }

    for _, controller := range f.Controllers {
        for k, v := range controller.ResponseData {
            switch k {
            case "Drive /c0/e31/s0","Drive /c0/e31/s1":
                var ds []DriveStruct
                if err := json.Unmarshal(*v, &ds); err == nil {
                    fmt.Println(k, ds)
                }
            case "Drive /c0/e31/s1 - Detailed Information":
                var dds1 DriveDetailedInformation1
                if err := json.Unmarshal(*v, &dds1); err == nil {
                    fmt.Println(k, dds1)
                }
            case "Drive /c0/e31/s0 - Detailed Information":
                var dds DriveDetailedInformation
                if err := json.Unmarshal(*v, &dds); err == nil {
                    fmt.Println(k, dds)
                }
            }
        }
    }
}

我认为响应数据可以在一个结构中解析。

 类似资料:
  • 我有一个json字符串,如下所示: 我想从上面的json字符串中提取< code>name和< code>age的值。我看了这个在http://play.golang.org/p/YQgzP7KPp9 golang网站给出的例子 但是我的问题是json顶层的键是动态的。这意味着< code>bvu62fu6dq是动态的。我创建了这样的结构: 但不确定如何提取<代码>姓名 和<代码>年龄 。我的代码

  • 问题内容: 我在将以下格式的json数据解组到结构时遇到麻烦。json的结构对我来说有点令人困惑,因此我为解组它所做的所有愚蠢的事情表示歉意。 我正在尝试使用以下结构将其解组。 这些字段在生成时将是未知的,并且会发生变化,并且存在此字段 在没有外部密钥的服务器名称之后,这再次让我感到困惑。我尝试了很多组合以了解如何将其解组,但是我失败了。 什么是使json字段解组为结构的有效方法? 问题答案: 您

  • 在我的笔记本电脑(MSI GE63VR 7RE)上,按下空格键(和其他一些键)时,GLFW将GLFW_KEY_传递给键回调函数未知的键。 几乎所有的钥匙都有扫描码,但这些钥匙应该是特定于机器的,没有方便的方法将它们映射到正确的钥匙名称。 为什么GLFW不能识别我的空间密钥GLFW_KEY_SPACE,解决这个问题的最佳方法是什么? 我在arch linux与wayland和我使用glfw-wayl

  • 问题内容: 我似乎找不到使用Dart语言在没有密钥的情况下解析json数组的解决方案。我所能找到的就是使用Java。我需要解析这样的内容。 Java解决方案来自这里 如果我有重复的问题,请告知我。谢谢! 问题答案: 只需json.decode正常使用,例如: 碰巧的成员l都将int小号

  • 问题内容: 我试图从下面的curl输出中获取说“ ip”的值: 我在互联网上发现了许多示例来解析curl请求的json输出,并且编写了以下代码,但这似乎并没有给我说“ ip”的值 如果有人可以向我提示我需要添加到代码中以获得“ ip”值的提示,我将不胜感激。 问题答案: 您可以创建结构来模仿json结构,然后对json进行解码。 输出为: 通过将其解码为一个结构,您可以循环遍历任何切片,而不会局限

  • 问题内容: 有没有办法用python向json添加重复键? 据我了解,python词典中不能有重复的键。通常,创建json的方法是先创建字典,然后再创建。但是,我需要在JSON中使用重复的键进行测试。但是我不能这样做,因为我不能在python字典中添加重复的键。我正在尝试在python 3中做到这一点 问题答案: 您总是可以手动构造这样的字符串值。 另一方面,可以使 C* Python 模块对重复