Transform JSON with /UI2/CL_JSON deserialize then serialize - json

I need to transform JSON.
I am getting output as "0000010006 GLAESS", but I need {"customer_id":"0000010006","customer":"GLAESS"}
TYPES: BEGIN OF ty_field,
customer_id TYPE string,
address TYPE string,
created_time TYPE string,
customer TYPE string,
date_created TYPE string,
END OF ty_field,
BEGIN OF ty_record,
id TYPE string,
createdtime TYPE string,
fields TYPE ty_field,
END OF ty_record,
BEGIN OF ty_response,
records TYPE STANDARD TABLE OF ty_record WITH EMPTY KEY,
END OF ty_response.
DATA:ls_response TYPE ty_response.
START-OF-SELECTION.
DATA(resp) = `{"records":[{"id":"rec5Qk24OQpKDyykq","createdTime":"2022-08-03T10:14:43.000Z","fields":{"customer_id":"0000010001","address":"Chennai","time_created":"06:00:14","customer":"IDADMIN","date_created":"16.04.2004"}},{"id":"rec7bSe8` &&
`Zb18z6b5a","createdTime":"2022-08-08T13:07:16.000Z","fields":{"customer_id":"0000010007","address":"Kakinada","time_created":"04:01:18","customer":"Ramya","date_created":"15.04.2000"}},{"id":"recD9Hh4YLgNXOhUE","createdTime":"2022-08-08T11:48:06.00` &&
`0Z","fields":{"customer_id":"0000010002","address":"Bangalore","time_created":"04:03:35","customer":"MAASSBERG","date_created":"20.04.2004"}},{"id":"recK7Tfw4PFAedDiB","createdTime":"2022-08-03T10:14:43.000Z","fields":{"customer_id":"0000010005","a` &&
`ddress":"Kakinada","time_created":"12:55","customer":"Lakshmi","date_created":"13-10-2022"}},{"id":"recKOq0DhEtAma7BV","createdTime":"2022-08-03T10:14:43.000Z","fields":{"customer_id":"0000010006","address":"Hyderabad","time_created":"18:42:28","cu` &&
`stomer":"GLAESS","date_created":"21.04.2004"}},{"id":"recS8pg10dFBGj8o7","createdTime":"2022-08-03T10:14:43.000Z","fields":{"customer_id":"0000010003","address":"Gurugram","time_created":"04:10:02","customer":"MAASSBERG","date_created":"20.04.2004"` &&
`}},{"id":"recf4QbOmKMrBeLQZ","createdTime":"2022-08-03T10:14:43.000Z","fields":{"customer_id":"0000010004","address":"Bangalore","time_created":"06:00:12","customer":"IDADMIN","date_created":"21.04.2004"}},{"id":"recs7oHEqfkN87tWm","createdTime":"2` &&
`022-08-03T10:14:43.000Z","fields":{"customer_id":"0000010000","address":"Hyderabad","time_created":"04:01:18","customer":"MAASSBERG","date_created":"15.04.2004"}}]}`.
/ui2/cl_json=>deserialize(
EXPORTING
json = resp
pretty_name = /ui2/cl_json=>pretty_mode-user
CHANGING
data = ls_response ).
DATA(ls_first_entry) = ls_response-records[ 5 ].
DATA(opt) = ls_first_entry-fields-customer_id && ` ` && ls_first_entry-fields-customer .
DATA(output) = /ui2/cl_json=>serialize(
data = opt
compress = abap_true
pretty_name = /ui2/cl_json=>pretty_mode-camel_case ).

If you want to serialize to a JSON object, you must use the corresponding ABAP structure. Currently you are serializing an abap string to json, that's why you get a simple json string.
TYPES: BEGIN OF ty_serialize,
customer_id TYPE string,
customer TYPE string,
END OF ty_serialize.
" Note: we build a structure, and not a string
DATA(ls_serialize) = VALUE ty_serialize( customer_id = ls_first_entry-fields-customer_id customer = ls_first_entry-fields-customer ).
DATA(lv_json1) = /ui2/cl_json=>serialize( data = ls_serialize
compress = abap_true
pretty_name = /ui2/cl_json=>pretty_mode-low_case ).
" Result: {"customer_id":"0000010006","customer":"GLAESS"}

Related

Powerquery: table function with variable parameter list length

How to write table function with non fixed parameter list length?
Particular simplified example:
I want to write function trimupper(TableName,ColumnName1,ColumnName2,...) that combines just two steps for given set of columns:
TRIM whitespaces
UPPERCASE text
Example for two columns case:
(tbl as table, cn1 as text, cn2 as text) =>
let
#"Trimmed Text" = Table.TransformColumns(tbl,{{cn1, Text.Trim , type text}, {cn2, Text.Trim , type text}}),
#"Uppercased Text" = Table.TransformColumns(tbl,{{cn1, Text.Upper, type text}, {cn2, Text.Upper, type text}}),
trimupperResult = #"Uppercased Text"
in
trimupperResult
But how to do it for variable number of ColumnNames?
let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
changethem = transform (Source,{"ColumnName1","ColumnName2"})
in changethem
function transform
(Table as table, columnnames as list) =>
let columnnames = if columnnames = null then Table.ColumnNames(Table) else columnnames,
change = Table.TransformColumns( Table, List.Transform(columnnames, each {_, Text.Trim, type text} ) ),
change1 = Table.TransformColumns( change, List.Transform(columnnames, each {_, Text.Upper, type text} ) )
in change1

Convert LUA table/json to KEY=VAL

I need to convert a lua table to KEY=VAL
e.g:
local t1 = {
t0 = "valt0",
t1 = "valt1",
tN = {
t0key = "t0var",
t1key = "t1var",
}
}
to be
t0="valt0", t1="valt1", tN_t0key="t0var", tN_t1key="t1var"
somebody have suggestions?
Make a function that loops through the table, checking if the value is table, in which case feed that table back into the same function. for anything that isn't a table, write it out to your new flattened table. Depending on how likely it is to happen, you might want to check there are no cyclic reference by tracking tables you've already iterated through.
local t1 = {
t0 = "valt0",
t1 = "valt1",
t2 = 42,
tN = {t0key = "t0var",
t1key = "t1var"}
}
local function convert(t)
local arr = {}
local cyclic = {}
local function convert_subtable(t, prefix)
assert(not cyclic[t], 'Cannot convert: cyclic reference detected')
cyclic[t] = true
for k, v in pairs(t) do
k = prefix..tostring(k)
if type(v) == 'number' or type(v) == 'boolean' then
table.insert(arr, k..'='..tostring(v))
elseif type(v) == 'table' then
convert_subtable(v, prefix..k..'_')
else
table.insert(arr, k..'='..string.format('%q', tostring(v)))
end
end
cyclic[t] = nil
end
convert_subtable(t, '')
table.sort(arr)
return table.concat(arr, ', ')
end
print(convert(t1)) --> t0="valt0", t1="valt1", t2=42, tN_t0key="t0var", tN_t1key="t1var"

fetch column name from json array

i need to get column name from the json array and ccompare with the column name with the sqlite table and have to alter the table when the column name dowsnot exists.
i use the code to fetch the column and column name from sqlite by this code
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null );
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for( int i=0 ; i< totalColumn ; i++){
cursor.getColumnName(i);
here i use "cursor.getColumnName() " to get the column name from the sqlitetable.
like this is this possible to fetch the column name from the JSONArray
example
cursor.getColumnName(resultSet.getJSONArray(i);
is this possible, else give me solution to get the column name of JSONArray value.
i have to compare the column names of JSONArray and the sqlite table.

Inserting multiple values and fields into table with anorm

I found this answer that solves to one field -> Inserting multiple values into table with anorm
var fields: List[String] = Nil
var values: List[(String,ParameterValue[_])] = Nil
for ((username,i) <- usernames.zipWithIndex) {
fields ::= "({username%s})".format(i)
values ::= ("username" + i, username)
}
SQL("INSERT INTO users (username) VALUES %s".format(fields.mkString(",")))
.on(values: _*)
.executeUpdate()
How can I pass more fields, like username, address, phonenumber, etc?
I tried ...
def create(names: List[(String,ParameterValue[_])] ,addresses :List[(String,ParameterValue[_])]){
var fields: List[String] = Nil;
for((a,i) <- names.zipWithIndex){
fields ::= "({name%s},{address%s})".format(i)
}
DB.withConnection { implicit c =>
SQL("insert into table (name,address) values %s".format(fields.mkString(",")))
.on(names: _*, addresses: _*)
.executeUpdate()
}
}
I get the following error:
" no "_ *" annotation allowed here"
If I could use one single list to all parameters it'll even better.
You basically want to perform a batch insert. Here's an adaptation taken from the docs:
import anorm.BatchSql
val batch = BatchSql(
"INSERT INTO table (name, address) VALUES({username}, {address})",
Seq(names, addresses)
)
val res: Array[Int] = batch.execute() // array of update count

DateTime error when updating rows using EF

I have a method that gets an existing row from a table in my database and updates some values on it and then save those changes. The table in quesiton has these columns:
The code that does the updating is here:
public void Update(Accommodation accommodation, string code, int supplierId)
{
var existingAccommodation = Get(a => a.Code == code && a.SupplierId == supplierId);
DateTime now = DateTime.Now;
existingAccommodation.ModifiedDate = now;
existingAccommodation.Description = accommodation.Description;
existingAccommodation.Introduction = accommodation.Introduction;
existingAccommodation.Name = accommodation.Name;
existingAccommodation.Strapline = accommodation.Strapline;
existingAccommodation.Type = accommodation.Type;
existingAccommodation.Processed = true;
DataContext.SaveChanges();
}
The problem is that the line DataContext.SaveChanges(); causes an exception whose innerexception says:
The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value
This is where the above code is called
Accommodation existingAccommodation = GetByCode(code, supplierId);
if (existingAccommodation != null)
{
_accommodationRepository.Update(
accommodation, code, existingAccommodation.SupplierId);
}