In the first part of the code, I am returning 6 instances with their values from the dataset, now I would like to be able to return an index value for each instance just like the picture below:
I am new to JSON and I do not know how to combine the last part with the first part of the code. I would appreciate your help in this regard. Thank you!
Well, the first thing to note is that script will end after the ‘return’ statement in the top part of the code. That’s why nothing in the bottom is being executed. You need to modify the list that you’re trying to return in script, and once it’s completely modified, then return it.
I might be misunderstanding what you’re trying to achieve, but if looks like you’re trying to return the dataset as JSON and add an “index” field that increments to each row. An easy way to achieve this would be to do something akin to this:
x = 0
list = []
pyData=system.dataset.toPyDataSet(value)
for row in pyData:
dict = {"mes_spec": row["spec"], "spec_rev": row["spec_rev"], .... , "index": x}
list.append(dict)
x += 1
return list
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
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
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.
What @lrose said. But also, you’re trying to embed procedural code (a for loop) inside an expression (returning a dictionary inside a list). Once you begin an expression, everything inside it must also be an expression. The .append() method is not an expression. Assignments of any kind (=, +=, etc.) are also not valid in expressions.