如何规范化这个递归嵌套 JSON

How to normalize this recursive nested JSON

尝试使用 Normalizr 规范化包含与父级相同类型的嵌套模式的我的有效负载时遇到一些问题

例如

{
  id: 123,
  sections:{
    section: [{
      id: 1,
      name: "test",
      sections: {
        section: {
          id: 125,
          name: "test125"
        }
      }
    }, {
      id: 2,
      name: "test2"
      sections: {
        section: [
          {
            id: 124,
            name: "test124"
          }
        ]
      }
    }, {
      id: 3,
      name: "test3"
    }]
  } 
}

在上面的json结构中,nested section可以是对象也可以是数组。

这是一个 jq 过滤器,它将规范化数据:

def enumerate:
  if type=="array" then .[] else . end ;
def sectionids:
    [ .sections.section | enumerate | .id // empty | tostring ]
  | if .==[] then {} else {sections:.} end ;
def sections:
    {sections:{section:[.]}}
  | .. | .section? | enumerate | objects | del(.sections) + sectionids ;

{
  "result": .id,
  "entities": {
    "sections": (reduce sections as $s ({};.["\($s.id)"]=$s))
  }
}

示例 运行(假设 data.json 中的适当 json 数据和 filter.jq 中的上述过滤器)

$ jq -M -f filter.jq data.json
{
  "result": 123,
  "entities": {
    "sections": {
      "123": {
        "id": 123,
        "sections": [
          "1",
          "2",
          "3"
        ]
      },
      "1": {
        "id": 1,
        "name": "test",
        "sections": [
          "125"
        ]
      },
      "2": {
        "id": 2,
        "name": "test2",
        "sections": [
          "124"
        ]
      },
      "3": {
        "id": 3,
        "name": "test3"
      },
      "125": {
        "id": 125,
        "name": "test125"
      },
      "124": {
        "id": 124,
        "name": "test124"
      }
    }
  }
}

Try it online!

我对嵌套评论也有类似的问题。这是我解决它的方法:

export const comment = new schema.Entity("comment", {}, {
    idAttribute: "key"
})
comment.define({
    user: user,
    reactions: {
        data: [reaction]
    },
    children: [comment]
})


export const post = new schema.Entity("post", {
    user: user,
    files: [image],
    comments: {
        data: [comment]
    },
    reactions: {
        data: [reaction]
    }
}, {
    idAttribute: "key"
})

基本上,我先将 comment 定义为一个新实体,然后再将其用于自己的实体定义中。我在构造函数中照常定义的其他模式(请参阅 post 模式作为示例)。希望这有帮助。