Question
· Mar 17, 2020

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 = list

This one doesn't like me that much as I am using %ZEN.Auxiliary. 

Discussion (4)2
Log in or sign up to continue

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 array

Using the JSON Adaptor.

Simple example:

Class dc.test Extends (%RegisteredObject%JSON.Adaptor)
{

Property list As list Of %String;

/// d ##class(dc.test).test()
ClassMethod test()
{
  json={"list":["green","yellow,red","blue"]}
  
  t=..%New()
  t.%JSONImport(json)
  t.list.Count(),!,t.list.GetAt(2)
}

}

USER>##class(dc.test).test()
3
yellow,red

Also look at Using Document Database (DocDB).

Another option without %ZEN.Auxiliary:

Class dc.mylist Extends %ListOfDataTypes
{

Method SizeSet(newvalue As %IntegerAs %Status
{
  i%Size=newvalue
  q $$$OK
}

}


Class dc.test Abstract ]
{

/// d ##class(dc.test).test()
ClassMethod test()
{
  json=["green","yellow,red","blue"]
  t=##class(%Document.Object).CSON(json.%ToJSON())
  
  l=##class(dc.mylist).%New()
  
  l.Data=t."_data"
  zk l.Data
  s l.Size=t.Count()
  
  l.Count(),!,l.GetAt(2)
}

}