How to fix Viper unmarshal error for nested structs

workplace with laptop and ceramic vase with basket

In times when you’re trying to unmarshal a config file using viper, check whether your config file has nested yaml structures.

  api_key: some_api_key
      api_key: some_api_key

As shown in the example above, there are multiple layers of structs under providers (i.e. payment contains dwolla). The different with service is that its fields are set only in one level.

If your config file is a single level struct, then there won’t be any problems using the yaml Golang structural flag. However, if your config file uses multiple-level structs as in the case of providers, then you need to use mapstructure instead of yaml when defining your structs.

See this stack overflow resource for more information.

I’ll build out a small reproducible repository to demonstrate this later.

Explore, Learn, and Thrive: Tech and Gaming with Darren

Hello, reader! I’m Darren, and I’m passionate about technology, learning, and gaming. My articles cater to mid to senior-level software engineers seeking to expand their knowledge and skills.

Through sharing our experiences and lessons learned (including our mistakes), we can inspire, support, and empower the next generation of engineering problem solvers. Documenting these insights also helps me reinforce their importance and ensure they remain in my memory.

In my blog, you’ll find a collection of mental models designed to help you tackle challenges in both your engineering career and personal life. Additionally, I share personal reflections and short stories, exploring parallels between competitive gaming and workplace performance.

Join me on this journey to learn and grow together!

2 responses to “How to fix Viper unmarshal error for nested structs”

  1. tables Avatar

    Thanks foг sharing your info. I truly appreⅽiate your efforts and I will be
    waiting for your neҳt post thank you once again.

    1. darrensapalo Avatar

      You’re welcome! Let me know if you have any questions or need any help.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.