Question
As a result of an API request to a third-party service, an array of data is received:
[
{
"domain": "some-domain.com",
"visible": 0,
"ads": 0
},
{
"domain": "another-domain.io",
"visible": 0,
"ads": 0
}
]
I add it to the table (create rows):
=: insertList(table: 'api_test'; field: 'name' = $json_extr[[domain]]; field: 'keywords' = $json_extr[[visible]]; field: 'ads' = $json_extr[[ads]])
~json_extr: jsonExtract(text: $api)
api: "here getFromScript"
An error occurred: Key domain
not found in one of the array elements. It indeed might be missing, as this is how the requested server provides it. What can be done?
Answer
This issue can be resolved in several ways:
Filter by non-empty value in domain
and skip those rows where it is absent using skip: true
:
=: insertList(table: 'api_test'; field: 'name' = $filter[[domain]]; field: 'keywords' = $filter[[visible]]; field: 'ads' = $filter[[ads]])
~filter: listFilter(list: $json_extr; key: "domain" != ""; skip: true)
json_extr: jsonExtract(text: $api)
api: "here getFromScript"
Iterate over all rows using listReplace and write the domain key to all rows with the condition that if the data in the original array for this key exists — take it, if it does not exist — write an empty value:
=: insertList(table: 'api_test'; field: 'name' = $replace[[domain]]; field: 'keywords' = $replace[[visible]]; field: 'ads' = $replace[[ads]])
~replace: listReplace(list: $json_extr; action: "domain" = $domain; value: "value")
json_extr: jsonExtract(text: $api)
api: "here getFromScript"
domain: $#value[domain]