Looping through JSON

  1. Don’t use ‘List’ as a variable name. This is a terrible practice even if you know it’s wrong and you’re only writing test code. Just kick the habit of using python built in names as variables, so nothing like
list,dict,str,int,tuple,set,float

should ever be used as variable names. And there are many others besides those

  1. You can enumerate the instances and add the index to them in the for loop with the enumerate() function.

Something like this should do:

	instances = [
		{
			'mes_spec':spec,
			'spec_rev':spec_rev,
			'name':name,
			'description':description,
			'state':state,
			'findings':findings,
			'low_limit': low,
			'process_value': proc,
			'high_limit': high,
			'units':units
		} for spec,spec_rev,name,description,state,findings,low, proc, high, units in system.dataset.toPyDataSet(value)
	]

    for r,i in enumerate(instances):
    	i['index'] = r

    return instances
  1. It should be noted that what you are doing here isn’t truly JSON, to the Jython this just looks like a list of dictionaries and you can treat it that way.
4 Likes