Grasshopper to JSON difficulty

I am new to Python and am not much familiar with JSON structure. But I need to compile animation data for a bunch of mirrors. I used json.dumps() but I don’t know how to work with data tree in Python. Can someone give me a hint, please?

I have two data trees with identical structure, where each branch represents one “frame” and contains movement data for 91 servos. Is there a simple way how to compile one single JSON from that data?

JSON should look like this (just an example):

{	"animation": "my_animation",
	"frames":
	[
		{   "frame":1,
			"movements":[ 
			   {  "mirror":1,
				  "ud":20,
			  	  "lr":20
               },
			   {  "mirror":2,
				  "ud":20,
				  "lr":20
               },
			   {  "mirror":3,
				  "ud":1,
				  "lr":10
               }
			]
		},
		{   "frame":2,
			"movements":[ 
			   {  "mirror":1,
				  "ud":22,
			  	  "lr":25
               },
			   {  "mirror":2,
				  "ud":50,
				  "lr":54
               },
			   {  "mirror":3,
				  "ud":85,
				  "lr":21
               }
			]
		}
	]
}

Grasshopper file with internalised data: animation_JSON.gh (88.7 KB)

This is what I wanted to achieve:

Pozn%C3%A1mka%202019-10-04%20095111

The general approach I use is to structure all my data into a Python dictionary (i.e. dict() or {}) and then json.dumps(myDict) this dictionary. Note that only primitive data types can be JSON dumped like this (i.e. not RhinoCommon geometry types etc. You can pickle a lot of these though).

Thanks. I tried to understand dictionary yesterday but it seems like it makes some strange data order by itself. So I tried to use list of dicts, but this was not so successful as I was not able to work with it within one python component (because of data trees) so I had to flatten it first, but this only worked when I converted my data to string. Maybe iterate through branches and iterate also through all data in each branch, combining them to list of lists? Or list of dicts?

Dictionaries are unordered, you can use OrderedDict() to preserve order. Do note that I’ve experienced some odd performance behaviours with those in IronPython (i.e. GHPython).

I would definitely separate the DataTree logic from the dict/json logic. That is, first read in all your DataTrees and make nested Python lists from these, than add/structure these into your dict, then dump this to a json file.