Store property coming from a json array
Hi,
I know there are several alternatives, but I would like to find the easiest & simpler ones to store data coming in Json format from post requests and also allowing me to do SQL queries.
I want to have a property called favouriteColors. I want to store a few colors, and I want to be able to do queries to get top favorite colors, etc... so not handling the list of colors as just a fixed string or fixed object.
If I want to store this information, I have several alternatives, like %DynamicArray, list of %String o maybe just %String, but I want to find the best way to store the property in a way that I can do SQL queries like
select COUNT(colors %FOREACH FavoriteColors) from Table
And an easy way to get the object from HTTP:
FavouriteColors = ["green","yellow","blue"]
and save it.
My initial idea is
FavouriteColors as list of %String
But then, the way to save from JSON received via POST doesn't like me. I did something like
d ##class(%ZEN.Auxiliary.jsonProvider).%ConvertJSONToObject(valueRecived.%ToJSON(),,.list)
Set table.FavouriteColors = listThis one doesn't like me that much as I am using %ZEN.Auxiliary.
Comments
Hello @Mario Sanchez Macias ,
I think it's not a correct usage of %ConvertJSONToObject, the third argument must be a target object instance.
Depending on your need, you should use "%Array of %String". It's more flexible for SQL that "%List".
If "valueRecived" variable is a dynamic array like ["green","yellow","blue"], you can test this code :
Set valueRecived = ["green","yellow","blue"]
Set array = ##class(%ArrayOfDataTypes).%New()
Do ##class(%ZEN.Auxiliary.jsonProvider).%ConvertJSONToObject(valueRecived.%ToJSON(),,.array)
Zw arrayNo need to init the array object:
Set valueRecived = ["green","yellow","blue"]
Do ##class(%ZEN.Auxiliary.jsonProvider).%ConvertJSONToObject(valueRecived.%ToJSON(),,.array)
Zw array
So you didn't find another simpler alternatives to %ConvertJSONToObject from the %ZEN package?
I will report to my colleagues from development, as not sure using %ZEN is the best way to do this.
Thanks
Mario
Simple example:
Class dc.test Extends (%RegisteredObject, %JSON.Adaptor)
{
Property list As list Of %String;
/// d ##class(dc.test).test()
ClassMethod test()
{
s json={"list":["green","yellow,red","blue"]}
s t=..%New()
d t.%JSONImport(json)
w t.list.Count(),!,t.list.GetAt(2)
}
}
USER>d ##class(dc.test).test()
3
yellow,redAlso look at Using Document Database (DocDB).
Another option without %ZEN.Auxiliary:
Class dc.mylist Extends %ListOfDataTypes
{
Method SizeSet(newvalue As %Integer) As %Status
{
s i%Size=newvalue
q $$$OK
}
}
Class dc.test [ Abstract ]
{
/// d ##class(dc.test).test()
ClassMethod test()
{
s json=["green","yellow,red","blue"]
s t=##class(%Document.Object).CSON(json.%ToJSON())
s l=##class(dc.mylist).%New()
m l.Data=t."_data"
zk l.Data
s l.Size=t.Count()
w l.Count(),!,l.GetAt(2)
}
}