'How to represent a nested array as one-dimensional array?

How to represent (serialise) an arbitrarily nested array, as a one-dimensional array of values (and meta-data) so that the original nested array and it's structure can be recreated from the serialised one-dimensional array?

I'm looking for a space efficient algorithms for this problem.

For example:

[
  [
    [1, 2, 3, 4]
  ], 
  [
    [5, 6, 7, 8], 
    [9, 10]
  ]
]

Should be serialised / deserialised to / from something like this

[/* elements of meta data* /, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source