Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

parsing data sequence into list #230

Closed
vanloswang opened this issue Dec 14, 2016 · 3 comments
Closed

parsing data sequence into list #230

vanloswang opened this issue Dec 14, 2016 · 3 comments

Comments

@vanloswang
Copy link

The data is

-
  ip: 192.168.1.1
  role: master
-
  ip: 192.168.1.2
  role: node
-
  ip: 192.168.1.3
  role: node

The struct is

type NODE struct {
	node []struct {
		ipaddr string
		role   string
	} `yaml:",flow"`
}

The parsing code is

	n := NODE{}

	err := yaml.Unmarshal([]byte(data), &n)
	if err != nil {
		log.Fatalf("error: %v", err)
	}
	fmt.Printf("--- t:\n%v\n\n", n)

then it failed with following infos:

2016/12/14 17:13:39 error: yaml: unmarshal errors:
  line 2: cannot unmarshal !!seq into main.NODE
@alexraju91
Copy link

@vanloswang I'm getting this same error. How did you solve this?

@colinodell
Copy link

@alexforever86 Did you ever find a solution?

@colinodell
Copy link

After struggling with this for a couple hours, I figured it out 5 minutes after pinging this thread (apologies for that!) The comment in #101 (comment) was a huge help.

In my case, I was trying to parse Ansible's requirements.yaml file which looks like this:

---
- src: franklinkim.php5-newrelic
- src: geerlingguy.composer
- src: geerlingguy.java
- src: geerlingguy.nginx
- src: geerlingguy.nodejs
- src: geerlingguy.php
- src: geerlingguy.php-versions
- src: geerlingguy.rabbitmq
- src: geerlingguy.solr
- src: newrelic.newrelic-infra

- name: mycustomrole
  src: git@gitlab.example.com:foo/bar.git
  scm: git
  version: master

- src: https://github.com/nickhammond/ansible-logrotate
  name: nickhammond.logrotate

I had a struct like this, which was correct:

type AnsibleSource struct {
	Source  string  `yaml:"src"`
	Name    *string `yaml:"name,omitempty"`
	Type    *string `yaml:"scm,omitempty"`
	Version *string `yaml:"version,omitempty"`
}

But to properly unmarshall the top-level sequence (and solve the cannot unmarshal !!seq error) I had to unmarshall it via var out []AnsibleSource like so:

	source, err := ioutil.ReadFile(ansibleRequirements.Path)
	if err != nil {
		return
	}

	var out []AnsibleSource

	err = yaml.Unmarshal(source, &out)
	if err != nil {
		return
	}

	fmt.Println(requirements)

Hope this helps someone else!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants