My problem is: how to traverse the json file?
I can iterate over keys (or values) but I don't get it for traversing
depth...
This rather depends how much you can rely on in regard to the JSON file's structure. I'm going to assume that you are not building a generic solution to traverse all possible JSON files?
(BTW goggle "JSON Schema" if you haven't come across the idea -- there are Ruby libraries that will help you validate your JSON, if you can define the structure.)
So if you know, for example, that the top level should be a key :foo which should contain an array, then it seems to me that the simplest way to proceed would be to iterate through the array and build an array of objects of class Foo -- each of which would take their array element as an initialiser.
If your JSON is a deeply nested Hash (for example, for the Foo class above) and you know the structure, you can just `@boz = json_string[:bar][:baz][:boz]`. Or use dig() if you prefer.
I would prefer traversing over recursion, but perhaps recursion is easier?
I would say that if you are looking to traverse an arbitrary data structure depth-wise, recursion is the way to go. But it really depends on the data structure and what you are trying to get out of it -- and how comfortable you are with recursion.
I might also say "don't try to traverse an arbitrary data structure depth-wise if you can possibly help it, that sounds like a hell of a lot of work".
Any ideas how to do that? (build a tree containing all keys and
array-items (array-beginning if item its linear, meaning nothing in the
level below)
You can do that trivially with JSON.parse. I mean, a tree of all keys and data items is what you get when you parse JSON into Ruby, right? The real trick is to make sense of the tree afterwards?
For which, at the end of the day, you will have to know *something* about its structure...
Click here to view Company Information and Confidentiality Notice.<http://www.jameshall.co.uk/index.php/small-print/email-disclaimer>