Skip to content
Advertisement

Seach in JSON with variable depth and structure

I have some highly nested JSON files I need to work with.

A short example:

JavaScript

I would now like to read all names from the JSON file and write them into a list. This is not particularly difficult if the JSON file has a fixed structure. However, my JSON files have a variable structure and variable depth. Sometimes everything happens on one level, but there are also files that go up to level 4 or 5. I would now like to create a variable solution that iterates over all layers of the JSON and searches for certain keys.

I have already tried something in the following direction, but I always get error messages.

JavaScript

Error:

JavaScript

Maybe someone has a code sample that could solve my problem and from which I could develop an idea for myself?

Advertisement

Answer

You can define this function:

JavaScript

And then you can use it like this (data is your json data):

JavaScript

Let’s do an example. This is your input data:

JavaScript

Here is the output:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement