6

大佬们求解一个 go map 无序的问题

 3 years ago
source link: https://www.v2ex.com/t/780962
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  Go

大佬们求解一个 go map 无序的问题

  liyaojian · 20 小时 29 分钟前 · 1076 次点击

要求:需要根据用户传入的 jsonStr 中的nameuser_id的顺序拼接其值。

package main

import (
	"encoding/json"
	"fmt"
	"reflect"
)

func main() {
	jsonStr := `{"name":"tom","user_id":"123"}` // 这是传入的参数,name 与 user_id 顺序不能确定先后
	var str string
	m := make(map[string]interface{})
	_ = json.Unmarshal([]byte(jsonStr), &m)
	
	v := reflect.ValueOf(m)
	keys := v.MapKeys()
	for _, key := range keys {
		v1 := v.MapIndex(key).Interface().(string)
		str += v1
	}
	fmt.Println(str)
	// 由于 map 无序,不能固定输出:tom123
	// 如何保持与 json 中键一致,固定输出?
	// 比如若 json_str := `{"user_id":"123""name":"tom"}` 则输出 123tom
}

在线运行: https://play.golang.org/p/_ZMfsISpKWz

还请大佬们赐教,感激不尽。

第 1 条附言  ·  18 小时 27 分钟前

非常感谢各位献计! 8 楼的方案可以解决我的问题。可能是表述不准确,应该是:由于 map 的无序,想求个其他方案解题。

关于做啥?是用在数据签名这块的,有历史遗留问题,如果现在重新设计,我也不会考虑这种奇葩的拼接方式。

再次感谢各位大佬。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK