Handling JSON in TouchDesigner

First, lets pur our JSON-String into a new textDAT and name it jsonstring

{	"Display1":	{	"Resolution"	:	{ "x":1920, "y":1080},
				"Refreshrate"	:	60},
	"Display2":     {	"Resolution"	:	{ "x":1280, "y":720},
				"Refreshrate"	:	50} 

Then we create another textDAT for our little script. First we need to import the json-module. Then we use the loads function to convert the jsonstring to a dictionary.
We can then acces the different member by using [ ] and the key.

import json
json_string = op('jsonstring').text
json_dict = json.loads( json_string )
debug( json_dict['Display1']['Refreshrate'] )

The textport will print out 60. If we would change Display1 for Display2, we would get 50 as our statement.
The structure we created is a dictionary. A very powerfull tool for data-organisation. To create a dictionary from scretch in python there are two way. The first one looks extremyl similiar, as the syntax is basicly lifted directly from json.

json_dict = {	"Display1":{"Resolution"	:	{ "x":1920, "y":1080},
							"Refreshrate"	:	60},
		"Display2":{"Resolution"	:	{ "x":1280, "y":720},
							"Refreshrate"	:	60} 


This line of could will give us 1920 in the textport.
The Alternative is to create an empty dictionary, and fill in the keys manually in the code itself.

json_dict = {}
json_dict['Display1'] = {}
json_dict['Display1']['Resolution'] = { 'x' : 1920, 'y' : 1080}

To convert a dictionary back to a json string, we can use the dumps function. The dumps function also allows us to pass an aditional argument, indent, to describe how manny space should be set for every level of depth we are in the structure. Without passing that argument, the whole string will be in a single line. For saving the string in pretty for for humans to read, and indent of 4 is a good meassure. So, lets create a new textDAT as a target and name it jsondict and write a new script.

import json
json_dict = {	"Display1":{"Resolution"	:	{ "x":1024, "y":1024},
			    "Refreshrate"	:	25},
		"Display2":{"Resolution"	:	{ "x":512, "y":512},
			    "Refreshrate"	:	25} 
json_string = json.dumps(json_dict, indent = 4)
op('jsonstring').text = json_string