Разбор Json с помощью Golang - PullRequest
0 голосов
/ 24 мая 2019

Я пытаюсь разобрать json с помощью go, но я не уверен насчет структуры данных, которую я строю. Выводом всегда является пустой объект.

структура данных:

{
  "Catalog": {
    "Name": "TypeMime",
    "Version": "1.0",
    "ObjectType": {
      "Area": 2,
      "Service": 2,
      "Version": 1,
      "Number": 117
    },
    "Items": [
      {
        "ItemNamespace": "application",
        "Name": "binhex-bin",
        "Oid": null,
        "Uid": 2201,
        "DocMandatoryProperties": [],
        "DocOptionalProperties": [
          "Subsystem",
          "Label",
          "Description"
        ],
        "DocVersionProperties": [],
        "DefaultAction": null,
        "Extensions": [
          ".bin"
        ],
        "Confidentiality": [
          "confidentiality/Public"
        ],
        "Converter": [],
        "Editor": [
          "gedit"
        ],
        "DiffEditor": [
          "kompare"
        ],
        "Icon": "",
        "IdentificationPattern": [
          "^\\S+.bin$"
        ]
      },
      {other items}
}
type ObjectType struct {
    Area int `json:"Area"`
    Service int `json:"Service"`
    Version int `json:"Version"`
    Number int `json:"Number"`
}
type Catalog struct {
    Name string `json:"Name"`
    Version string `json:"Version"`
    ObjectType ObjectType `json:"ObjectType"`
    Items []Item `json:"Items"`
}
type Item struct {
    ItemNamespace string `json:"ItemNamespaceItems"`
    Name string `json:"Name"`
    Oid int `json:"Oid"`
    Uid int `json:"Uid"`
    DocMandatoryProperties []string `json:"DocMandatoryProperties"`
    DocOptionalProperties []string `json:"DocOptionalProperties"`
    DocVersionProperties []string `json:"DocVersionProperties"`
    DefaultAction string `json:"DefaultAction"`
    Extensions []string `json:"Extensions"`
    Confidentiality []string `json:"Confidentiality"`
    Converter []string `json:"Converter"`
    Editor []string `json:"Editor"`
    DiffEditor []string `json:"DiffEditor"`
    Icon string `json:"Icon"`
    IdentificationPattern []string `json:"IdentificationPattern"`
}

    var catalog Catalog

    // Open our jsonFile
    jsonFile, err := os.Open("path.json")
    // if we os.Open returns an error then handle it
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("Successfully Opened json")
    // defer the closing of our jsonFile so that we can parse it later on
    defer jsonFile.Close()
    byteValue, err := ioutil.ReadAll(jsonFile)
    if err != nil {
        fmt.Println("error input file :",err)
    }
    err = json.Unmarshal(byteValue, &catalog)
    if err != nil {
        fmt.Println("error input file :",err)
    }
    fmt.Println("catalog from json : ",catalog)

Я получаю этот вывод: {{0 0 0 0} []}

Так что я думаю, может быть, построенные мной структуры не верны или Go не может обрабатывать "нулевые" значения. Файл JSON правильно открыт и преобразован в байты, я не получаю никаких ошибок, только не то, что ожидал, т. Е. Анализ json в моей переменной Catalog.

Есть предложения?

1 Ответ

2 голосов
/ 24 мая 2019
err = json.Unmarshal(byteValue, &catalog)

Вы говорите go, что собираетесь разбирать каталог, но затем делаете что-то еще. Что вы на самом деле делаете, так это даете ему (неназванный) объект, который имеет ключ «Каталог» с соответствующим значением. Go не может найти ни одного ключа каталога в этом объекте, и поэтому вы получаете все пустые поля.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...