Define “cyclic data structures”

前端 未结 9 1818
鱼传尺愫
鱼传尺愫 2021-02-02 09:33

At the JSON site it says

JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.

<
9条回答
  •  日久生厌
    2021-02-02 10:10

    I guess the textbook example of a cyclic structure is the doubly-linked list. Each element points to the previous and next elements in the list. This means each element forms a cycle with the previous and next element.

    A --> B  --> C
    A <-- B  <-- C
    

    (Here each A, B, C although written twice is one object.)

    A points to B, as next in the list. B points to A as previous in the list. So there is a cycle from A to B and back to A. The same is true for every element in the list, with elements not at the head or tail beloning to two cycles.

    One solution to serializing lists like this is to use IDs to represent each object. This removes the cycles in the structure. We could then write out

      list: {
         items:
          { id:"a", value1: ... etc },
          { id:"b", values .... },
          { id:"c", values .... }
         links:
           { elem:"a", next:"b" },
           { elem:"b", next:"c", prev: "a"},
           { elem:"c", prev:"b" }
      }
    

提交回复
热议问题