• 请不要在回答技术问题时复制粘贴 AI 生成的内容
anankun
V2EX  ›  程序员

关于带层级的列表转 json 对象的问题

  •  
  •   anankun · Mar 25, 2021 · 2408 views
    This topic created in 1924 days ago, the information mentioned may be changed or developed.

    原始数据

    数据库里有这样的一些数据

    _id p_id parm_key parm_value parm_type
    0 -1 template object
    10 0 name template-name string
    20 0 inputs object
    201 20 parameters [object]
    2011 201 name this-is-name-1 string
    2012 201 value this-is-value-1 string
    2013 201 name this-is-name-2 string
    2014 201 value this-is-value-2 string

    其中:

    • id 和 p_id 是表示层级关系的
    • parm_key 对应的是某个对象的属性名称
    • parm_value 是 parm_type 为 string 时的属性值

    需求

    要根据上述的数据结构,生成以下格式的 json 对象或者 json 字符串:

    {
        "template": {
            "name": "template-name",
            "inputs": {
                "parameters": [
                    {
                        "name": "this-is-name-1",
                        "value": "this-is-value-1"
                    },
                    {
                        "name": "this-is-name-2",
                        "value": "this-is-value-2"
                    }
                ]
            }
        }
    }
    

    用什么样的方法能够做到这种转换呢?

    5 replies    2021-03-25 15:36:13 +08:00
    66beta
        1
    66beta  
       Mar 25, 2021
    递归,遍历树
    anankun
        2
    anankun  
    OP
       Mar 25, 2021
    递归是可以,想一想实现起来有点忒麻烦
    0x666666
        3
    0x666666  
       Mar 25, 2021
    递归
    no1xsyzy
        4
    no1xsyzy  
       Mar 25, 2021
    如果 (parm_key, parm_type) 对的种类固定且不多的话可以用 GraphQL,只要写出相当于 (parm_key, parm_type) 那么多个 key 就行了。
    不然你还是老老实实游走树吧。
    Xbluer
        5
    Xbluer  
       Mar 25, 2021
    Entity 中多加属性 parent 和 childList.

    List<Entity> 转换成一个 Map<_id, Entity>。遍历 list,使用 map 把 entity 中的 parent 赋值,并把当前 entity 添加岛 parent.childList 中。如果 map 中查询结果是 null,那就是树的 root 。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   951 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 21:59 · PVG 05:59 · LAX 14:59 · JFK 17:59
    ♥ Do have faith in what you're doing.