Home  >  Article  >  Backend Development  >  Unable to extract key/value pairs from map obtained via YAML

Unable to extract key/value pairs from map obtained via YAML

王林
王林forward
2024-02-08 23:40:29368browse

无法从通过 YAML 获取的映射中提取键/值对

php editor Xiaoxin often encounters a problem when using YAML to obtain mappings, that is, the key/value pairs cannot be extracted from the mapping obtained through YAML. This problem is very common in actual development, and it may cause the configuration file to be unable to be read correctly or the correct data to be obtained. In this article, we will delve into the cause of this problem and provide some solutions to help developers extract key/value pairs more smoothly when using YAML.

Question content

I use the goldmark-meta package to read yaml files. What I'm interested in is this In yaml:

burger:
- a: ay
- b: bee
- c: see

I want to access keys and values Returning to the interface, I'm stuck. The iteration returns me a a list of key/value pairs, but I don't have know how to get any information when i don't know Know the key names ahead of time. The program prints out the following:

func (c *config) burger() string {
    // c.pagefm is type map[string]interface{}
    b, ok := c.pagefm["burger"].([]interface{})
    if !ok {
    // no burger entry  in yaml
        return ""
    }
  debug("burger list has %v items:\n%v", len(b), b)  
  debug("type: %v", reflect.typeof(b))
  for i := 0; i < len(b); i++ {
    debug("%v", b[i])
  }
 return ""
}
Burger list has 3 items:
[map[a:ay] map[b:bee] map[c:see]]
Type: []interface {}
map[a:ay]
map[b:bee]
map[c:see]

How to get the key and value string?

Workaround

In your yaml data, you have a key (burger) whose value is a list of mappings (each map has a key). We can iterate over the items in burger like this:

b, ok := c.pagefm["burger"].([]interface{})
if !ok {
  return ""
}

for _, item := range burger {
  ...
}

For each item, we can iterate over the available keys and values:

for _, item := range burger {
  for k, v := range item.(map[interface{}]interface{}) {
    ...
  }
}

We can use fmt.sprintf to convert the keys and values ​​in interface{} to string:

for _, item := range burger {
  for k, v := range item.(map[interface{}]interface{}) {
    k_str := fmt.sprintf("%v", k)
    v_str := fmt.sprintf("%v", v)

    fmt.printf("key %s value %s\n", k_str, v_str)
  }
}

Starting with sample code from goldmark-meta, I put together this example:

package main

import (
    "bytes"
    "fmt"

    "github.com/yuin/goldmark"
    meta "github.com/yuin/goldmark-meta"
    "github.com/yuin/goldmark/parser"
)

func main() {
    markdown := goldmark.new(
        goldmark.withextensions(
            meta.meta,
        ),
    )
    source := `---
burger:
- a: ay
- b: bee
- c: see
---

# hello goldmark-meta
`

    var buf bytes.buffer
    context := parser.newcontext()
    if err := markdown.convert([]byte(source), &buf, parser.withcontext(context)); err != nil {
        panic(err)
    }
    metadata := meta.get(context)
    burger := metadata["burger"].([]interface{})
    for _, item := range burger {
        for k, v := range item.(map[interface{}]interface{}) {
            k_str := fmt.sprintf("%v", k)
            v_str := fmt.sprintf("%v", v)
            fmt.printf("key %s value %s\n", k_str, v_str)
        }
    }
}

Which outputs:

key a value ay
key b value bee
key c value see

The above is the detailed content of Unable to extract key/value pairs from map obtained via YAML. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete