草庐IT

json - 解析嵌套列表不会下降到第 3 级

coder 2024-07-08 原文

我有一个表示菜单项的 JSON。

一个菜单项可以有一个子菜单项,子菜单项又可以有另一个子菜单项等等。

输入 JSON 通过父 ID 关联菜单项。我正在尝试将其转换为一个模型,其中每个菜单项都有其子菜单项的一部分。

子菜单分为三层。我已经设法解析了两个级别,但我不知道为什么不解析第三个级别。我已经调试这个问题好几个小时了。我将不胜感激。

menu2.sjon

[
  {
    "category_id": 4,
    "category_id_400": "'SCHOO",
    "name": "School Supplies",
    "parent_id": 2,
    "position": 2,
    "level": 2,
    "status": 1,
    "url": "http://www.booksrus.kw/sa-en/school-supplies.html"
  },
  {
    "category_id": 141,
    "category_id_400": "'SCHBA",
    "name": "School Bags",
    "parent_id": 4,
    "position": 12,
    "level": 3,
    "status": 1,
    "url": "http://www.booksrus.kw/sa-en/school-supplies/school-bags.html"
  },
  {
    "category_id": 269,
    "category_id_400": "'AEP",
    "name": "Bags Knapsack with Trolley",
    "parent_id": 141,
    "position": 1,
    "level": 4,
    "status": 1,
    "url": "http://www.booksrus.kw/sa-en/school-supplies/school-bags/bags-knapsack-with-trolley.html"
  }
]

menu.go

package main

import(
    "fmt"
    "encoding/json"
    "io/ioutil"
    "sort"
    "bytes"
)

type MenuItems []MenuItem

func (a MenuItems) Len() int           { return len(a) }
func (a MenuItems) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a MenuItems) Less(i, j int) bool { return a[i].Category_id < a[j].Category_id }

type MenuItem struct{
    Category_id int `json:"category_id"`
    Category_id_400 string `json:"category_id_400"`
    Name string `json:"name"`
    Parent_id int `json:"parent_id"`
    Position int `json:"position"`
    Level int `json:"level"`
    Status int `json:"status"`
    Url string  `json:"url"`
    Subs []MenuItem `json:"subs"`
}

func (m MenuItem) String() string{

     var buffer bytes.Buffer
     buffer.WriteString(fmt.Sprintf("%d %s\n",m.Category_id,m.Name))
    for _,s := range m.Subs{
        buffer.WriteString(fmt.Sprintf(">   %s\n",s.String()));
    }

    return buffer.String()
    //return fmt.Sprintf("CategoryId: %d, ParentId: %d,Name: %s, Sub: %v\n",m.Category_id,m.Parent_id,m.Name,m.Subs);
}

func (m *MenuItem) TryAdd(other MenuItem) bool{

    if other.Parent_id == m.Category_id {

        m.Subs = append(m.Subs,other);
        return true
    }else{
        for _,sub := range m.Subs{
            if found := sub.TryAdd(other);found{
                return true
            }
        }
    }

    return false
}

func main() {
    rootItems := make([]MenuItem,0)
    bytes, err := ioutil.ReadFile("menu2.json")

    if err != nil{
        fmt.Printf("Reading: %s\n",err.Error())
        return;
    }

    var menuItems []MenuItem
    err = json.Unmarshal(bytes,&menuItems)

    if err != nil{
        fmt.Println(err.Error())
        return
    }

    sort.Sort(MenuItems(menuItems))

    for _,item := range menuItems{
        if item.Parent_id == 2{
            rootItems = append(rootItems,item)
        }else{
            for i:=0;i<len(rootItems);i++{
                if found := rootItems[i].TryAdd(item); found{
                    break;
                }else{
                    fmt.Printf("No Action: Id: %d, Name: %s, Parent: %d.\n",item.Category_id,item.Name,item.Parent_id)
                }
            }
        }
    }

    fmt.Printf("\nRootitems:\n%s\n",rootItems)
}

输出

Rootitems:
[4           School Supplies
>   141           School Bags
//Third level should appear here
]

最佳答案

TryAdd 函数中的这个循环很可能是您的问题:

for _, sub := range m.Subs {
    if found := sub.TryAdd(other); found {
        return true
    }
}

此循环中的 sub 变量实际上是 slice 元素的副本。您在那里所做的任何更改都不会保留回存储在 slice 中的元素。

你应该能够通过不使用元素的副本来解决这个问题,而是通过它的索引来引用它:

for i := range m.Subs {
    if found := m.Subs[i].TryAdd(other); found {
        return true
    }
}

关于json - 解析嵌套列表不会下降到第 3 级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34841327/

有关json - 解析嵌套列表不会下降到第 3 级的更多相关文章

  1. Ruby 解析字符串 - 2

    我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?

  2. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  3. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  4. ruby - 将散列转换为嵌套散列 - 2

    这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[

  5. ruby - 用逗号、双引号和编码解析 csv - 2

    我正在使用ruby​​1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\

  6. ruby - Highline 询问方法不会使用同一行 - 2

    设置:狂欢ruby1.9.2高线(1.6.13)描述:我已经相当习惯在其他一些项目中使用highline,但已经有几个月没有使用它了。现在,在Ruby1.9.2上全新安装时,它似乎不允许在同一行回答提示。所以以前我会看到类似的东西:require"highline/import"ask"Whatisyourfavoritecolor?"并得到:Whatisyourfavoritecolor?|现在我看到类似的东西:Whatisyourfavoritecolor?|竖线(|)符号是我的终端光标。知道为什么会发生这种变化吗? 最佳答案

  7. ruby - RVM 使用列表[0] - 2

    是否有类似“RVMuse1”或“RVMuselist[0]”之类的内容而不是键入整个版本号。在任何时候,我们都会看到一个可能包含5个或更多ruby的列表,我们可以轻松地键入一个数字而不是X.X.X。这也有助于rvmgemset。 最佳答案 这在RVM2.0中是可能的=>https://docs.google.com/document/d/1xW9GeEpLOWPcddDg_hOPvK4oeLxJmU3Q5FiCNT7nTAc/edit?usp=sharing-知道链接的任何人都可以发表评论

  8. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  9. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  10. Ruby——嵌套类和子类是一回事吗? - 2

    下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby​​解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc

随机推荐