如何进行深度设置并进入Go的地图[string] interface {}? [英] How to do deep sets and gets in Go's map[string]interface{}?

查看:100
本文介绍了如何进行深度设置并进入Go的地图[string] interface {}?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一些任意的JSON,我怎样才能做深层次的设置,并使用切片索引和/或切片索引获取嵌套属性?

If I have some arbitrary JSON how can I do deep sets and gets on the nested properties using a slice of map keys and/or slice indexes?

,在以下摘自 JSON API示例的摘录中:

For example, in the following excerpt from the JSON API example:

{
    "data": [{
        "type": "posts",
        "id": "1",
        "title": "JSON API paints my bikeshed!",
        "links": {
            "self": "http://example.com/posts/1",
            "author": {
                "self": "http://example.com/posts/1/links/author",
                "related": "http://example.com/posts/1/author",
                "linkage": { "type": "people", "id": "9" }
            }
        }
    }]
}

我想要字符串9位于 data.0.links.author.linkage.id 使用类似于:

I'd like to get the string "9" located at data.0.links.author.linkage.id using something like:

[]interface{}{"data",0,"links","author","linkage","id"}

我知道理想的方式要做到这一点是创建映射到我为生产代码做的JSON对象的嵌套结构,但有时我需要做一些快速测试,这在Go中也是很好的。

I know the ideal way to do this is to create nested structs that map to the JSON object which I do for production code, but sometimes I need to do some quick testing which would be nice to do in Go as well.

推荐答案

您有 stretchr / objx 提供了类似的方法。

You have stretchr/objx that provide a similar approach.

使用示例:

Example use:

document, _ := objx.FromJSON(json)
document.Get("path.to.field[0].you.want").Str()

但是,除非您真的不知道JSON输入的结构, ,这不是golang的首选方式......

However, unless you really don't know at all the structure of your JSON input ahead of time, this isn't the preferred way to go in golang…

这篇关于如何进行深度设置并进入Go的地图[string] interface {}?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆