当前位置: 首页 > 知识库问答 >
问题:

如何散集嵌套的未知字段

彭琛
2023-03-14

我在这里分叉了一个很棒的项目,并且一直在学习一些东西。我无法弄清楚的问题是关于自定义解编的一些事情,如果您看到这里,您可以看到这解封了包含数据接口{}字段的事物结构,然后使用Kind字符串字段解组。除了嵌套情况外,这一切都很好用。所以最好的事情是一个例子:

假设你有一个< code>Thing结构,它是一个< code>listing,也就是< code>Thing。数据这被解组为类型< code >列表。那么< code>listing有3个< code>link类型的< code>Children,保存在< code>Children []Thing字段中。这些子元素最终属于< code > map[string]interface { } 类型,这是我的问题。我怎样才能通过嵌套数据解组呢?这样< code >的孩子。数据也被解组。在go中有办法做到这一点吗?或者我必须写一个大的循环或者递归算法?请让我知道你是怎么想的,或者我是否对这种情况的看法完全错误。谢谢你

这里更新的是一个json示例

{
    "kind": "Listing",
    "data": {
        "after": null,
        "dist": 10,
        "facets": {},
        "modhash": null,
        "whitelist_status": "all_ads",
        "children": [
            {
                "kind": "t3",
                "data": {
                    "domain": "self.nanocurrency",
                    "approved_at_utc": null,
                    "mod_reason_by": null,
                    "banned_by": null,
                    "num_reports": null,
                    "subreddit_id": "t5_2wlj3",
                    "thumbnail_width": null,
                    "subreddit": "CryptoCurrency",
                    "selftext_html": null,
                    "selftext": "",
                    "likes": null,
                    "suggested_sort": null,
                    "crosspost_parent_list": [
                        {
                            "domain": "self.nanocurrency",
                            "approved_at_utc": null,
                            "mod_reason_by": null,
                            "banned_by": null,
                            "num_reports": null,
                            "subreddit_id": "t5_4br49",
                            "thumbnail_width": null,
                            "subreddit": "nanocurrency",
                            "selftext_html": "&lt;!-- SC_OFF --&gt;&lt;div class=\"md\"&gt;&lt;p&gt;Seeing lots of comments about the lack of timestamps in the protocol, and just wanted to provide some information on why objectively accurate, global time timestamps are an illusion in decentralized systems. Logical time on the other hand is achievable and is in fact achieved in Nano via the individual block chains and the directed, acyclic graph (DAG). &lt;/p&gt;\n\n&lt;p&gt;Generally, in a decentralized, distributed system, only logical time (C happened after B happened after A) can be agreed on globally (e.g. Lamport time: &lt;a href=\"https://amturing.acm.org/p558-lamport.pdf\"&gt;https://amturing.acm.org/p558-lamport.pdf&lt;/a&gt; or vector clocks). This is what the nano ledger does via chaining blocks, just as any other blockchain. Then it connects those chains via a DAG. Syncing global time to logical time is a hard problem that can either be approached via a consensus approach which is prone to sybil attacks, via a probabilistic approach which is what most blockchains go with - essentially relying on their peers - or a centralized approach like NTP which is a no-go in a decentralized system. If you&amp;#39;re interested, check e.g. this paper: &lt;a href=\"http://soft.vub.ac.be/%7Etvcutsem/distsys/clocks.pdf\"&gt;http://soft.vub.ac.be/~tvcutsem/distsys/clocks.pdf&lt;/a&gt;&lt;/p&gt;\n\n&lt;p&gt;So what you&amp;#39;re running into is the problem that while theoretically all or a relevant subset of nodes within the Nano or Bitcoin or Ethereum network could agree to call a certain time &amp;quot;Monday February 12 2018 20:35:23&amp;quot;, this timestamp could still be incorrect vs the outside world.&lt;/p&gt;\n\n&lt;p&gt;That&amp;#39;s why any accurate global timestamps in software today rely on centralized information and trusted entities. The only way this can change is if machines start setting their clocks on their own accurately (e.g. chip-scale atomic clocks)&lt;/p&gt;\n\n&lt;p&gt;Some people think this is bad news for Nano because in traditional blockchain, timestamps are fairly important because they are used in new block validation: &lt;a href=\"http://culubas.blogspot.co.uk/2011/05/timejacking-bitcoin_802.html\"&gt;http://culubas.blogspot.co.uk/2011/05/timejacking-bitcoin_802.html&lt;/a&gt; . Timestamps are a blessing and a curse at the same time in blockchain: They allow for timing and validation of blocks and therefore regulation of coin mining, but also allow for timestamp double spend attacks. Since Nano does not use mining, it is not susceptible to those attacks.&lt;/p&gt;\n\n&lt;p&gt;Even with the relative importance of time and timestamps in Bitcoin, timestamp in Bitcoin are not guaranteed to be corresponding to logical time on the chain. Here&amp;#39;s the bitcoin wiki talking about the bitcoin block timestamp: &lt;a href=\"https://en.bitcoin.it/wiki/Block_timestamp\"&gt;https://en.bitcoin.it/wiki/Block_timestamp&lt;/a&gt; &lt;/p&gt;\n\n&lt;blockquote&gt;\n&lt;p&gt;A timestamp is accepted as valid if it is greater than the median timestamp of previous 11 blocks, and less than the network-adjusted time + 2 hours. &amp;quot;Network-adjusted time&amp;quot; is the median of the timestamps returned by all nodes connected to you. As a result, block timestamps are not exactly accurate, and they do not even need to be in order. Block times are accurate only to within an hour or two. &lt;/p&gt;\n&lt;/blockquote&gt;\n\n&lt;p&gt;This is probably as good as it gets. Still no ordering guarantees though, and a possibilities for attacks which have been discussed again and again. There are certain guards in Bitcoin code to prevent these from happening. &lt;/p&gt;\n\n&lt;p&gt;So if you have somebody lecturing you about how architecturally superior coins would have a accurate and monotonically increasing timestamps, point them here, or here: &lt;a href=\"https://cointelegraph.com/news/timestamp-hacking-debunking-the-myth-of-precision-timestamps\"&gt;https://cointelegraph.com/news/timestamp-hacking-debunking-the-myth-of-precision-timestamps&lt;/a&gt;&lt;/p&gt;\n\n&lt;p&gt;Would timestamps be convenient to have on the protocol? Yes, and that would likely be a good reason to include them. Are timestamps accurately depicting global time, and can they be used as evidence in any chain? No they can&amp;#39;t.&lt;/p&gt;\n\n&lt;p&gt;Why are we seeing inaccurate timestamps in the block explorer? Because these are kept in a db outside of the ledger and have been set January 19. Nothing more to it.&lt;/p&gt;\n\n&lt;p&gt;Why do people like to babble about how this is a weakness in Nano? No clue.&lt;/p&gt;\n&lt;/div&gt;&lt;!-- SC_ON --&gt;",
                            "selftext": "Seeing lots of comments about the lack of timestamps in the protocol, and just wanted to provide some information on why objectively accurate, global time timestamps are an illusion in decentralized systems. Logical time on the other hand is achievable and is in fact achieved in Nano via the individual block chains and the directed, acyclic graph (DAG). \n\nGenerally, in a decentralized, distributed system, only logical time (C happened after B happened after A) can be agreed on globally (e.g. Lamport time: https://amturing.acm.org/p558-lamport.pdf or vector clocks). This is what the nano ledger does via chaining blocks, just as any other blockchain. Then it connects those chains via a DAG. Syncing global time to logical time is a hard problem that can either be approached via a consensus approach which is prone to sybil attacks, via a probabilistic approach which is what most blockchains go with - essentially relying on their peers - or a centralized approach like NTP which is a no-go in a decentralized system. If you're interested, check e.g. this paper: http://soft.vub.ac.be/~tvcutsem/distsys/clocks.pdf\n\nSo what you're running into is the problem that while theoretically all or a relevant subset of nodes within the Nano or Bitcoin or Ethereum network could agree to call a certain time \"Monday February 12 2018 20:35:23\", this timestamp could still be incorrect vs the outside world.\n\nThat's why any accurate global timestamps in software today rely on centralized information and trusted entities. The only way this can change is if machines start setting their clocks on their own accurately (e.g. chip-scale atomic clocks)\n\nSome people think this is bad news for Nano because in traditional blockchain, timestamps are fairly important because they are used in new block validation: http://culubas.blogspot.co.uk/2011/05/timejacking-bitcoin_802.html . Timestamps are a blessing and a curse at the same time in blockchain: They allow for timing and validation of blocks and therefore regulation of coin mining, but also allow for timestamp double spend attacks. Since Nano does not use mining, it is not susceptible to those attacks.\n\nEven with the relative importance of time and timestamps in Bitcoin, timestamp in Bitcoin are not guaranteed to be corresponding to logical time on the chain. Here's the bitcoin wiki talking about the bitcoin block timestamp: https://en.bitcoin.it/wiki/Block_timestamp \n\n&gt; A timestamp is accepted as valid if it is greater than the median timestamp of previous 11 blocks, and less than the network-adjusted time + 2 hours. \"Network-adjusted time\" is the median of the timestamps returned by all nodes connected to you. As a result, block timestamps are not exactly accurate, and they do not even need to be in order. Block times are accurate only to within an hour or two. \n\nThis is probably as good as it gets. Still no ordering guarantees though, and a possibilities for attacks which have been discussed again and again. There are certain guards in Bitcoin code to prevent these from happening. \n\nSo if you have somebody lecturing you about how architecturally superior coins would have a accurate and monotonically increasing timestamps, point them here, or here: https://cointelegraph.com/news/timestamp-hacking-debunking-the-myth-of-precision-timestamps\n\nWould timestamps be convenient to have on the protocol? Yes, and that would likely be a good reason to include them. Are timestamps accurately depicting global time, and can they be used as evidence in any chain? No they can't.\n\nWhy are we seeing inaccurate timestamps in the block explorer? Because these are kept in a db outside of the ledger and have been set January 19. Nothing more to it.\n\nWhy do people like to babble about how this is a weakness in Nano? No clue.",
                            "likes": null,
                            "suggested_sort": null,
                            "user_reports": [],
                            "secure_media": null,
                            "is_reddit_media_domain": false,
                            "link_flair_text": null,
                            "id": "7ww6bm",
                            "banned_at_utc": null,
                            "mod_reason_title": null,
                            "view_count": null,
                            "archived": false,
                            "clicked": false,
                            "media_embed": {},
                            "report_reasons": null,
                            "author": "ohlookaballoon",
                            "num_crossposts": 2,
                            "saved": false,
                            "mod_reports": [],
                            "can_mod_post": false,
                            "is_crosspostable": true,
                            "pinned": false,
                            "score": 24,
                            "approved_by": null,
                            "over_18": false,
                            "hidden": false,
                            "thumbnail": "self",
                            "edited": false,
                            "link_flair_css_class": null,
                            "author_flair_css_class": null,
                            "contest_mode": false,
                            "gilded": 0,
                            "downs": 0,
                            "brand_safe": false,
                            "secure_media_embed": {},
                            "removal_reason": null,
                            "author_flair_text": null,
                            "stickied": false,
                            "can_gild": true,
                            "thumbnail_height": null,
                            "parent_whitelist_status": null,
                            "name": "t3_7ww6bm",
                            "spoiler": false,
                            "permalink": "/r/nanocurrency/comments/7ww6bm/why_global_time_objectively_accurate_timestamps/",
                            "subreddit_type": "public",
                            "locked": false,
                            "hide_score": false,
                            "created": 1518417258,
                            "url": "https://www.reddit.com/r/nanocurrency/comments/7ww6bm/why_global_time_objectively_accurate_timestamps/",
                            "whitelist_status": null,
                            "quarantine": false,
                            "title": "Why global time, objectively accurate timestamps are not achievable in decentralized systems",
                            "created_utc": 1518388458,
                            "subreddit_name_prefixed": "r/nanocurrency",
                            "ups": 24,
                            "media": null,
                            "num_comments": 18,
                            "is_self": true,
                            "visited": false,
                            "mod_note": null,
                            "is_video": false,
                            "distinguished": null
                        }
                    ],
                    "user_reports": [],
                    "secure_media": null,
                    "is_reddit_media_domain": false,
                    "link_flair_text": null,
                    "id": "7x3r45",
                    "banned_at_utc": null,
                    "mod_reason_title": null,
                    "view_count": null,
                    "archived": false,
                    "clicked": false,
                    "media_embed": {},
                    "report_reasons": null,
                    "author": "ohlookaballoon",
                    "num_crossposts": 0,
                    "saved": false,
                    "mod_reports": [],
                    "can_mod_post": false,
                    "is_crosspostable": true,
                    "pinned": false,
                    "score": 2,
                    "approved_by": null,
                    "over_18": false,
                    "hidden": false,
                    "thumbnail": "default",
                    "edited": false,
                    "link_flair_css_class": null,
                    "author_flair_css_class": "New",
                    "contest_mode": false,
                    "gilded": 0,
                    "downs": 0,
                    "brand_safe": true,
                    "secure_media_embed": {},
                    "removal_reason": null,
                    "author_flair_text": "Redditor for 27 days.",
                    "stickied": false,
                    "can_gild": true,
                    "thumbnail_height": null,
                    "parent_whitelist_status": "all_ads",
                    "name": "t3_7x3r45",
                    "crosspost_parent": "t3_7ww6bm",
                    "spoiler": false,
                    "permalink": "/r/CryptoCurrency/comments/7x3r45/why_global_time_objectively_accurate_timestamps/",
                    "subreddit_type": "public",
                    "locked": false,
                    "hide_score": false,
                    "created": 1518496223,
                    "url": "https://np.reddit.com/r/nanocurrency/comments/7ww6bm/why_global_time_objectively_accurate_timestamps/",
                    "whitelist_status": "all_ads",
                    "quarantine": false,
                    "title": "Why global time, objectively accurate timestamps are not achievable in decentralized systems",
                    "created_utc": 1518467423,
                    "subreddit_name_prefixed": "r/CryptoCurrency",
                    "ups": 2,
                    "media": null,
                    "num_comments": 0,
                    "is_self": false,
                    "visited": false,
                    "mod_note": null,
                    "is_video": false,
                    "distinguished": null
                }
            },

共有2个答案

郎宏逸
2023-03-14

在您的情况下,您需要创建一个递归函数来获取底层< code>interface{}的嵌套值,直到最后一个深度。我们无法从具有未知基础类型的< code>interface{}获取嵌套值。下面是一个你可以在代码中做什么的例子

桂梓
2023-03-14

这正是json所做的。RawMessage是for(查看文档中的解组示例)。首先对JSON对象的顶层进行解组,检查种类字段,然后对数据字段进行解组:

type Listing struct {                                           
    WhitelistStatus string  `json:"whitelist_status"`           
    Children        []Thing `json:"children"`                   
}                                                               

type T3 struct {                                                
    Domain              string `json:"domain"`                  
    CrosspostParentList []struct {                              
            Domain string `json:"domain"`                       
    } `json:"crosspost_parent_list"`                            
}                                                               

type Thing struct {
    Kind string      `json:"kind"`
    Data interface{} `json:"data"`
}

func (t *Thing) UnmarshalJSON(b []byte) error {
    var step1 struct {
            Kind string          `json:"kind"`
            Data json.RawMessage `json:"data"` 
    }

    if err := json.Unmarshal(b, &step1); err != nil {
            return err
    }

    var step2 interface{}
    switch step1.Kind {
    case "Listing":
            step2 = &Listing{}
    case "t3":
            step2 = &T3{}
    default:
            return errors.New("unknown kind: " + step1.Kind) // or simply ignore
    }

    if err := json.Unmarshal(b, step2); err != nil {
            return err
    }

    t.Kind = step1.Kind
    t.Data = step2

    return nil
}

在操场上试试:https://play.golang.org/p/giBVT2IWPd-

 类似资料:
  • 问题内容: 我在这里分叉了一个很棒的项目,并且刚刚学习了一些东西,就把它弄乱了。我不知道的问题是有关自定义编组的一些问题,如果您在这里看到,您可以看到它解组了包含一个字段的结构,然后使用该字段将其解组。除了嵌套的情况,这一切都很好。因此,最好的例子是: 只需说您有一个善意的结构是a ,那么就可以将其编组。然后具有3个保留在字段中的类型。这些孩子最终成为我的问题类型。我如何才能解决嵌套数据的问题?这

  • 问题内容: 我在Scala和Java之间遇到编译问题。 我的Java代码需要一个 我的scala代码有一个 我收到编译错误: 似乎scala.collection.JavaConversions不适用于嵌套集合,即使Vector可以隐式转换为Iterable。除了遍历scala集合并手动进行转换之外,我还能做些什么使这些类型起作用? 问题答案: 应该弃用恕我直言。您最好使用来明确说明转换的时间和地

  • 问题内容: 我想知道是否存在针对此类问题的简单解决方案。 我有一个对象注释,该对象注释又可以包含注释,并且这些注释也可以包含注释…并且此操作可以进行未知数量的循环。 这是数据结构的示例: 可以说我会写2级评论: 我该如何使div的嵌套注释达到“ n”级? 问题答案: 最简单的方法是创建通用部分,以便您可以使用递归调用和呈现它。 这是局部的: 数据模型应为列表。 我为您创建了一个演示,希望对您有所帮

  • 问题内容: 我有一个嵌套的数据结构。我想使用模块读取其键和值。数据结构像下面这样。 我试图使用波纹管方式读取字典中的键,但出现错误。 码 错误 所以任何人都可以解释错误的原因以及如何遍历字典。 问题答案: 作为请求的输出,代码如下所示 代替您也可以使用,但是效率更高并且返回迭代器。 希望这可以帮助 :)

  • 问题内容: 我在将以下格式的json数据解组到结构时遇到麻烦。json的结构对我来说有点令人困惑,因此我为解组它所做的所有愚蠢的事情表示歉意。 我正在尝试使用以下结构将其解组。 这些字段在生成时将是未知的,并且会发生变化,并且存在此字段 在没有外部密钥的服务器名称之后,这再次让我感到困惑。我尝试了很多组合以了解如何将其解组,但是我失败了。 什么是使json字段解组为结构的有效方法? 问题答案: 您

  • 问题内容: 假设我有一个像这样的领域模型: 现在,我可以像这样创建一个教师比较器: 但是,我如何像这样在嵌套字段上比较Lecture? 我无法在模型上添加方法。 问题答案: 您不能嵌套方法引用。您可以改用lambda表达式: 无需反向顺序,它就不再那么冗长了: 注意:在某些情况下,您需要明确声明泛型类型。对于 例如,下面的代码不会没有工作,之前在Java中8。 较新的Java版本具有更好的自动类型