golang depth read map
Foreword: I optimized and improved the below solution, and released it as a library here: github.com/icza/dyno
.
The cleanest way would be to create predefined types (structures struct
) that model your JSON, and unmarshal to a value of that type, and you can simply refer to elements using Selectors (for struct
types) and Index expressions (for maps and slices).
However if your input is not of a predefined structure, I suggest you the following 2 helper functions: get()
and set()
. The first one accesses (returns) an arbitrary element specified by an arbitrary path (list of string
map keys and/or int
slice indices), the second changes (sets) the value specified by an arbitrary path (implementations of these helper functions are at the end of the answer).
You only have to include these 2 functions once in your project/app.
And now using these helpers, the tasks you want to do becomes this simple (just like the python solution):
fmt.Println(get(d, "key3", 0, "c2key1", "c3key1"))
set("NEWVALUE", d, "key3", 0, "c2key1", "c3key1")
fmt.Println(get(d, "key3", 0, "c2key1", "c3key1"))
Output:
change1
NEWVALUE
Try your modified app on the Go Playground.
Note - Further Simplification:
You can even save the path in a variable and reuse it to simplify the above code further:
path := []interface{}{"key3", 0, "c2key1", "c3key1"}
fmt.Println(get(d, path...))
set("NEWVALUE", d, path...)
fmt.Println(get(d, path...))
And the implementations of get()
and set()
are below. Note: checks whether the path is valid is omitted. This implementation uses Type switches:
func get(m interface{}, path ...interface{}) interface{} {
for _, p := range path {
switch idx := p.(type) {
case string:
m = m.(map[string]interface{})[idx]
case int:
m = m.([]interface{})[idx]
}
}
return m
}
func set(v interface{}, m interface{}, path ...interface{}) {
for i, p := range path {
last := i == len(path)-1
switch idx := p.(type) {
case string:
if last {
m.(map[string]interface{})[idx] = v
} else {
m = m.(map[string]interface{})[idx]
}
case int:
if last {
m.([]interface{})[idx] = v
} else {
m = m.([]interface{})[idx]
}
}
}
}
golang depth read map的更多相关文章
- 记一次坑爹的golang 二维map判断问题
记一次坑爹的golang 二维map判断问题 2018年10月18日 23:16:21 yinnnnnnn 阅读数:32更多 个人分类: golang 版权声明:本文为博主原创文章,未经博主允许不 ...
- Golang基础教程——map使用篇
本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是golang专题的第7篇文章,我们来聊聊golang当中map的用法. map这个数据结构我们经常使用,存储的是key-value的键 ...
- Golang,用map写个单词统计器
Golang中也有实用的泛型编程模板.如map.据Go官方团队称,其实现为Hash表,而非类似cpp或Java的红黑树.所以理论上速度更能快上几个等级(Hash与红黑树的效率对比可以看我的文章C++中 ...
- Golang 入门 : 映射(map)
映射是一种数据结构,用于存储一系列无序的键值对,它基于键来存储值.映射的特点是能够基于键快速检索数据.键就像是数组的索引一样,指向与键关联的值.与 C++.Java 等编程语言不同,在 Golang ...
- Golang教程:Map
什么是 map? Map 是 Go 中的内置类型,它将键与值绑定到一起.可以通过键获取相应的值. 如何创建 map? 可以通过将键和值的类型传递给内置函数 make 来创建一个 map.语法为:mak ...
- golang struct 转map 及 map[string]*Struct 初始化和遍历
package main import ( "encoding/json" "errors" "fmt" "reflect&quo ...
- 深入理解golang:sync.map
疑惑开篇 有了map为什么还要搞个sync.map 呢?它们之间有什么区别? 答:重要的一点是,map并发不是安全的. 在Go 1.6之前, 内置的map类型是部分goroutine安全的,并发的读没 ...
- golang struct转map
struct转map package main import ( "fmt" "reflect" "time" ) type User st ...
- golang中,map作为函数参数是如何传递的
当你声明一个map的时候: m := make(map[int]int) 编译器会调用 runtime.makemap: // makemap implements a Go map creation ...
随机推荐
- veeValidate实战
说在前面 vee-validate 版本2.0.4的学习github地址我的项目地址第一次认真的在git上写一个demo教程,喜欢的可以star一下~^o^~ (^-^) (^o^) 后续会有一个完整 ...
- 解决laydate动态设置初始值的问题
//初始化//注意:我这里是时间范围选择,所以定义了range属性.var timeScope = laydate.render({ elem: '#time_scope', range: '~', ...
- javaScript第二篇
事件处理函数 javaScript响应用户操作等都是通过事件处理来触发;其基本形式为 event = "javaScript statement(s);" 事件 = "事 ...
- Program Transformation Semantics (程序转换语义学)
本文是Inside The C++ Object Model Chapter 2 部分的读书笔记.讨论编译器调用拷贝构造函数时的策略(如何优化以提高效率),侯捷称之为"程序转化的语义学&qu ...
- 【模板】OI常用模板(待补充)
//PS:最近修改日期:2017-11-07 20:41:44 首先感觉这种模板类的东西写了还是很有意义的,毕竟时不时的可以拿出来借鉴一下. 现在因为刚开始写这一类的东西,所以说还不是很详细,若有读者 ...
- 如何设计出优美的Web API?
概述 WEB API的应用场景非常丰富,例如:将已有系统的功能或数据开放给合作伙伴或生态圈:对外发布可嵌入到其他网页的微件:构建前后端分离的WEB应用:开发跨不同终端的移动应用:集成公司内部不同系统等 ...
- BeautifulSoup4 提取数据爬虫用法详解
Beautiful Soup 是一个HTML/XML 的解析器,主要用于解析和提取 HTML/XML 数据. 它基于 HTML DOM 的,会载入整个文档,解析整个 DOM树,因此时间和内存开销都会大 ...
- HDU 5115 Dire Wolf ——(区间DP)
比赛的时候以为很难,其实就是一个区间DP= =..思路见:点我. 区间DP一定要记住先枚举区间长度啊= =~!因为区间dp都是由短的区间更新长的区间的,所以先把短的区间更新完.. 代码如下: #inc ...
- [CSP-S模拟测试]:C(三分+贪心)
题目传送门(内部题46) 输入格式 第一行$3$个整数$n,m,t$.第二行$n$个整数,表示$P_i$.接下来$m$行每行两个整数,表示$L_i,R_i$. 输出格式 一行一个整数表示答案. 样例 ...
- 发送http请求和https请求的工具类
package com.haiyisoft.cAssistant.utils; import java.io.IOException;import java.util.ArrayList; impor ...