如何在Golang中将键值对格式的字符串转换为映射(map)?

huangapple go评论77阅读模式
英文:

How to convert key-value format string to map in golang?

问题

有一个格式化字符串如下:

"key1=value1&key2=value2"

如何将这个字符串优雅地转换为一个映射(map):

{"key1":"value1","key2":"value2"}

是否有像Guava的MapSplitter这样的好用工具?

英文:

There is a format string like this:

"key1=value1&key2=value2"

How to convert this string to a map elegantly:

{"key1":"value1","key2":"value2"}

Is there any good utils like Guava's MapSplitter?

答案1

得分: 2

你可以使用strings.Split()函数两次来将整个字符串按照&分割成key=value对,然后再次使用=将每个对分割成keyvalue

快速示例代码(不处理边界情况):https://go.dev/play/p/t8oMbA72GCB

英文:

You can use strings.Split() function twice to split the entire string into a key=value pairs by & and then again to split each pair to key and value by =.

Quick playground without handling corner cases: https://go.dev/play/p/t8oMbA72GCB

huangapple
  • 本文由 发表于 2022年12月15日 11:52:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/74806647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定