javascriptjsonflatten

Why and when do we need to flatten JSON objects?


I am surprised that no one on StackOverflow asked this question before.

Looking through the JSON object documentation and a quick google search did not yield satisfactory results.

What's the advantage of it? How does it work?


Edit: To make it clear, take a look at this flatten/un-flatten example.

Fastest way to flatten / un-flatten nested JSON objects

Thank you.


Solution

  • There are many situations where you get JSON text that was automatically built by some library. Throughout the programming languages, there are many libraries that build JSON text (one example is here).

    Whenever libraries add some additional object or array wrappings, you might want to get rid of them maybe because you send the JSON to the server and your code there crashes because it expects a primitive value instead of an object (or an array). Or, if your JSON is a server response, you don't want the resulting Javascript code having to differ between object/array or not object/array. In all these cases, flattening is helpful as it will save you time. You will have to implement less if/elses, and you can reliably expect your data structure to be as flat as possible.

    The other approach to improve code for the scenario mentioned is to write the code in a maximally robust way so there is no way for it to crash by superfluous wrappings ever. So always expect some wrappers and get its contents. Then, flattening is not needed.

    You see, it depends on what is building the JSON and what is parsing it. The building may be out of your scope.

    This leads also to data model questions. I've worked with XML code that needed to be parsed quite a different way if there were 0 entries of X, or if there were >0 entries of some X. Having a wrapper that is allowed to have 0 or more entries of X will make live easier. These are data model decisions.

    In all cases where the JSON represents an object structure that I've combined manually, I expect it not to change. So flattening something I've designed in detail would be disturbing. Standard operations as far I've seen them do not need flattening (e.g. JSON.stringify(), json_encode() etc.)