Maison  >  Article  >  développement back-end  >  Lecture d'un tableau à partir d'un fichier yaml dans GoLang

Lecture d'un tableau à partir d'un fichier yaml dans GoLang

WBOY
WBOYavant
2024-02-08 23:45:101204parcourir

从 GoLang 中的 yaml 文件读取数组

l'éditeur php Banana vous présentera comment lire des tableaux à partir de fichiers yaml dans GoLang dans cet article. GoLang est un langage de programmation puissant et les fichiers yaml sont un format de fichier utilisé pour stocker des données structurées. En lisant le tableau dans le fichier yaml, nous pouvons facilement obtenir les données qu'il contient et effectuer un traitement ultérieur. Cet article expliquera en détail les étapes à suivre pour lire un fichier yaml et fournira un exemple de code pour vous aider à mieux comprendre. Que vous soyez débutant ou développeur expérimenté, cet article vous fournira des conseils pratiques et des connaissances que vous pourrez facilement appliquer à vos projets. Commençons tout de suite !

Contenu de la question

J'essaie de lire un fichier yaml contenant un tableau d'objets

package config

import (
    "gopkg.in/yaml.v3"
    "log"
    "os"
    "path/filepath"
    "runtime"
)

type documentationinfo struct {
    docs []document `yaml:"document"`
}

type document struct {
    title    string `yaml:"title"`
    filename string `yaml:"filename"`
}

func (c *documentationinfo) init() map[string]document {
    _, b, _, _ := runtime.caller(0)
    basepath := filepath.dir(b)

    yamlfile, err := os.readfile(basepath + "/documentation.yaml")
    if err != nil {
        log.printf("yamlfile.get err   #%v ", err)
    }
    err = yaml.unmarshal(yamlfile, c.docs)
    if err != nil {
        log.fatalf("unmarshal: %v", err)
    }

    docinfo := make(map[string]document)

    for _, doc := range c.docs {
        docinfo[doc.filename] = doc
    }

    return docinfo
}
func newdocumentconfig() *documentationinfo {
    return &documentationinfo{}
}

fichier yaml

documentationinfo:
  document:
    - {filename: "foo.md", title: "i am an foo title"}
    - {filename: "test.md", title: "i am an test title"}
    - {filename: "bar.md", title: "i am an bar title"}
    - {filename: "nice.md", title: "i am an nice title"}

Erreur

2023/06/27 13:44:44 Unmarshal: yaml: unmarshal errors:
  line 1: cannot unmarshal !!map into []config.Document

Je ne sais pas si le problème vient de la syntaxe du fichier yaml car elle est similaire à json, mais la documentation de références croisées semble correcte.

Toutes les suggestions seraient grandement appréciées...

Solution de contournement

Vous avez défini le conteneur le plus externe avec un tableau de document 键的映射,其中包含 document :

type documentationinfo struct {
  docs []document `yaml:"document"`
}

Mais ce n'est pas la structure des données d'entrée, cela ressemble à ceci :

documentationinfo:
  document:
    - {filename: "foo.md", title: "i am an foo title"}
    - {filename: "test.md", title: "i am an test title"}
    - {filename: "bar.md", title: "i am an bar title"}
    - {filename: "nice.md", title: "i am an nice title"}

L'élément externe est un include documentationinfo 键的映射(该键的值是带有 document 键的映射)。您需要像这样重新定义您的类型(我已将其转换为 package main afin que je puisse l'exécuter localement pour le tester) :

package main

import (
    "fmt"
    "log"
    "os"
    "path/filepath"
    "runtime"

    "gopkg.in/yaml.v3"
)

type documentationinfofile struct {
    documentationinfo documentationinfo `yaml:"documentationinfo"`
}

type documentationinfo struct {
    docs []document `yaml:"document"`
}

type document struct {
    title    string `yaml:"title"`
    filename string `yaml:"filename"`
}

func (docinfo *documentationinfofile) init() map[string]document {
    _, b, _, _ := runtime.caller(0)
    basepath := filepath.dir(b)

    yamlfile, err := os.readfile(basepath + "/documentation.yaml")
    if err != nil {
        log.printf("yamlfile.get err   #%v ", err)
    }
    err = yaml.unmarshal(yamlfile, docinfo)
    if err != nil {
        log.fatalf("unmarshal: %v", err)
    }

    docmap := make(map[string]document)
    for _, doc := range docinfo.documentationinfo.docs {
        docmap[doc.filename] = doc
    }

    return docmap

}
func newdocumentconfig() *documentationinfofile {
    return &documentationinfofile{}
}

func main() {
    d := newdocumentconfig()
    docmap := d.init()
    fmt.printf("%+v\n", docmap)
}

L'exécution du code ci-dessus produira :

Frais 65bcd85880

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer