解组嵌套的 JSON 对象 [英] Unmarshaling nested JSON objects

查看:26
本文介绍了解组嵌套的 JSON 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a 很少 问题 topic 但它们似乎都没有涵盖我的情况,因此我正在创建一个新的.>

我有如下的 JSON:

{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}

有没有办法解组嵌套的 bar 属性并将其直接分配给结构属性而不创建嵌套结构?

我现在采用的解决方案如下:

type Foo struct {更多字符串`json:"more"`富结构{条形字符串`json:"bar"`Baz 字符串`json:"baz"`} `json:"foo"`//FooBar 字符串 `json:"foo.bar"`}

这是一个简化版本,请忽略冗长.如您所见,我希望能够解析并将值分配给

//FooBar 字符串 `json:"foo.bar"`

我见过有人使用地图,但我的情况并非如此.我基本上不关心foo(它是一个大对象)的内容,除了一些特定的元素.

在这种情况下,正确的方法是什么?我不是在寻找奇怪的黑客,因此如果这是要走的路,我没问题.

解决方案

有没有办法解组嵌套的 bar 属性并将其直接分配给结构属性而不创建嵌套结构?

不, encoding/json 不能像 encoding/xml 那样使用>some>deep>childnode"来解决这个问题.嵌套结构是可行的方法.

There are a few questions on the topic but none of them seem to cover my case, thus I'm creating a new one.

I have JSON like the following:

{"foo":{ "bar": "1", "baz": "2" }, "more": "text"}

Is there a way to unmarshal the nested bar property and assign it directly to a struct property without creating a nested struct?

The solution I'm adopting right now is the following:

type Foo struct {
    More String `json:"more"`
    Foo  struct {
        Bar string `json:"bar"`
        Baz string `json:"baz"`
    } `json:"foo"`
    //  FooBar  string `json:"foo.bar"`
}

This is a simplified version, please ignore the verbosity. As you can see, I'd like to be able to parse and assign the value to

//  FooBar  string `json:"foo.bar"`

I've seen people using a map, but that's not my case. I basically don't care about the content of foo (which is a large object), except for a few specific elements.

What is the correct approach in this case? I'm not looking for weird hacks, thus if this is the way to go, I'm fine with that.

解决方案

Is there a way to unmarshal the nested bar property and assign it directly to a struct property without creating a nested struct?

No, encoding/json cannot do the trick with ">some>deep>childnode" like encoding/xml can do. Nested structs is the way to go.

这篇关于解组嵌套的 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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