How to filter the Array of Dictionary if the dictionary elements are null? - objective-c

I need to filter the array of dictionary , but in my structure some of the values are null
"data": [
{
"date": "2019-04-12 00:00:00",
"points": 825,
"trips": [
{
"id": 108,
"trip_detail": “<null>”
}
},
{
"date": "2019-04-11 00:00:00",
"points": 2475,
"trips": [
{
"id": 73,
"trip_detail": {
"id": 53,
"score": 8.25,
"points": 825,
}
},
{
"id": 74,
"trip_detail": {
"id": 54,
"score": 8.25,
"points": 825,
}
},
so in the above result I need to remove the first array of dictionary as well as that array.

Use filter to loop over a collection and return an Array containing only those elements that match an include condition.

Related

JSON SQL column in azure data factory

I have a JSON type SQL column in SQL table as below example. I want the below code to be converted into separate columns such as drugs as table name and other attribute as column name, how can I use adf or any other means please guide. The below code is a single column in a table called report where I need to convert this into separate columns .
{
"drugs": {
"Codeine": {
"bin": "Y",
"name": "Codeine",
"icons": [
93,
103
],
"drug_id": 36,
"pathway": {
"code": "prodrug",
"text": "is **inactive**, its metabolites are active."
},
"targets": [],
"rxnorm_id": "2670",
"priclasses": [
"Analgesic/Anesthesiology"
],
"references": [
1,
16,
17,
100
],
"subclasses": [
"Analgesic agent",
"Antitussive agent",
"Opioid agonist",
"Phenanthrene "
],
"metabolizers": [
"CYP2D6"
],
"phenotype_ids": {
"metabolic": "5"
},
"relevant_genes": [
"CYP2D6"
],
"dosing_guidelines": [
{
"text": "Reduced morphine formation. Use label recommended age- or weight-specific dosing. If no response, consider alternative analgesics such as morphine or a non-opioid.",
"source": "CPIC",
"guidelines_id": 1
},
{
"text": "Analgesia: select alternative drug (e.g., acetaminophen, NSAID, morphine-not tramadol or oxycodone) or be alert to symptoms of insufficient pain relief.",
"source": "DPWG",
"guidelines_id": 362
}
],
"drug_report_notes": [
{
"text": "Predicted codeine metabolism is reduced.",
"icons_id": 58,
"sort_key": 58,
"references_id": null
},
{
"text": "Genotype suggests a possible decrease in exposure to the active metabolite(s) of codeine.",
"icons_id": 93,
"sort_key": 56,
"references_id": null
},
{
"text": "Professional guidelines exist for the use of codeine in patients with this genotype and/or phenotype.",
"icons_id": 103,
"sort_key": 50,
"references_id": null
}
]
}
Since this json is already in a SQL column, you don't need ADF to break it down to parts. You can use JSON functions in SQL server to do that.
example of few first columns:
declare #json varchar(max) = '{
"drugs": {
"Codeine": {
"bin": "Y",
"name": "Codeine",
"icons": [
93,
103
],
"drug_id": 36,
"pathway": {
"code": "prodrug",
"text": "is **inactive**, its metabolites are active."
},
"targets": [],
"rxnorm_id": "2670",
"priclasses": [
"Analgesic/Anesthesiology"
],
"references": [
1,
16,
17,
100
],
"subclasses": [
"Analgesic agent",
"Antitussive agent",
"Opioid agonist",
"Phenanthrene "
],
"metabolizers": [
"CYP2D6"
],
"phenotype_ids": {
"metabolic": "5"
},
"relevant_genes": [
"CYP2D6"
],
"dosing_guidelines": [
{
"text": "Reduced morphine formation. Use label recommended age- or weight-specific dosing. If no response, consider alternative analgesics such as morphine or a non-opioid.",
"source": "CPIC",
"guidelines_id": 1
},
{
"text": "Analgesia: select alternative drug (e.g., acetaminophen, NSAID, morphine-not tramadol or oxycodone) or be alert to symptoms of insufficient pain relief.",
"source": "DPWG",
"guidelines_id": 362
}
],
"drug_report_notes": [
{
"text": "Predicted codeine metabolism is reduced.",
"icons_id": 58,
"sort_key": 58,
"references_id": null
},
{
"text": "Genotype suggests a possible decrease in exposure to the active metabolite(s) of codeine.",
"icons_id": 93,
"sort_key": 56,
"references_id": null
},
{
"text": "Professional guidelines exist for the use of codeine in patients with this genotype and/or phenotype.",
"icons_id": 103,
"sort_key": 50,
"references_id": null
}
]
}
}
}
select JSON_VALUE(JSON_QUERY(#json,'$.drugs.Codeine'),'$.bin') as bin,
JSON_VALUE(JSON_QUERY(#json,'$.drugs.Codeine'),'$.name') as name,
JSON_VALUE(JSON_QUERY(#json,'$.drugs.Codeine'),'$.drug_id') as drug_id,
JSON_VALUE(JSON_QUERY(#json,'$.drugs.Codeine'),'$.icons[0]') as icon_1
'
You need to decide how to handle arrays, such as icons, where there are multiple values inside the same element.
References:
JSON_QUERY function
JSON_VALUE function

Karate: I get missing property in path $['data'] while using json filter path

I have gone through karate documentation and questions asked on stack overflow. There are 2 json arrays under resp.response.data. I am trying to retrieve and assert "bId": 81 in below json from the resp.response.data[1] but I get this missing property error while retrieving id value 81. Could you please help if I am missing something ?
* def resp =
"""
{
"response": {
"data": [
{
"aDetails": {
"aId": 15,
"aName": "Test",
"dtype": 2
},
"values": [
{
"bId": 45,
"value": "red"
}
],
"mandatory": false,
"ballId": "1231231414"
},
{
"aDetails": {
"aId": 25,
"aName": "Description",
"dtype": 2
},
"values": [
{
"bId": 46,
"value": "automation"
},
{
"bId": 44,
"value": "NESTED ARRAY"
},
{
"bId": 57,
"value": "sfERjuD"
},
{
"bId": 78,
"value": "zgSyPdg"
},
{
"bId": 79,
"value": "NESTED ARRAY"
},
{
"bId": 80,
"value": "NESTED ARRAY"
},
{
"bId": 81,
"value": "NESTED ARRAY"
}
],
"mandatory": true,
"ballId": "1231231414"
}
],
"corId": "wasdf-242-efkn"
}
}
"""
* def expectedbID=81
* def RespValueId = karate.jsonPath(resp, "$.data[1][?(#.bId == '" + expectedbID + "')]")
* match RespValueId[0] == expectedbID
Maybe you are over-complicating things ?
* match resp.response.data[1].values contains { bId: 81, value: 'NESTED ARRAY' }

Traversing JSON objects with tSQL - OPENJSON

I have the following JSON code. I pull the values into a SQL database using OPENJSON, but I am having trouble with the path for the Refund object.
I am trying to pull the "amount" value in the "transactions" object (so the expected value should be 298.47).
SQL code (currently returns only null values)
OPEN(json)
WITH(
OtherJSONstuff varchar '$otherjsonstuff'
Refund int '$.refund[0].transactions.amount' <what should this be
JSON Code
"otherjsonstuff": othervalues
"otherjsonstuff": othervalues
"object": [
{
"id": 212,
"items": [
{
"id": 151,
"quantity": 3,
"item_id": 926,
"subtotal": 30.0,
"tax": 0.0,
"item": {
"id": 926,
"quantity": 3,
"price": "10.00",
"product_id": 934,
"properties": [],
"discount": "0.00",
"tax": []
}
}
],
"action": [
{
"id": 537,
"amount": "298.47", --this is the line I need
"kind": "refund",
"created": "2016-12-13",
"location_id": null,
"parent_id": 537,
}
],
}
],
Having reformatted the JSON code,
it should be $.refund[0].transactions[0].amount
Depend on the array object you want to access, just increment and decrements the values. The root cause is understanding the JSON hierarchy and JNevil has provided you some good resources

Select game scores with a player's context from Postgres

I am developing a web app with rails and postgres as a shooting range game backend. It has an endpoint to save players scores, which writes the scores to DB and returns the first three places and the players' ranks with some context around it: a place before and a place after. For example if a player has rank 23, the method should return 1st, 2nd, 3rd places, the player rank itself and also two records with ranks 22 and 24 besides it. I don't store the rank in the DB it is calculated dynamically using following sql query:
SELECT RANK() OVER(ORDER BY score DESC) AS place, name, score
FROM scores
WHERE game_id=? AND rules_version=? AND game_mode=?
LIMIT 10
POST request with following data:
{
"players": [
{ "name": "Jack", "score": 100, "local_id": 1, "stats": {}},
{ "name": "Anna", "score": 200, "local_id": 2, "stats": {}}
]
}
should return following result set:
{
"scores": [
{
"name": "Piter",
"place": 1,
"score": 800
},
{
"name": "Lisa",
"place": 2,
"score": 700
},
{
"name": "Philip",
"place": 3,
"score": 600
},
{
"name": "Max",
"place": 25,
"score": 204
},
{
"name": "Anna",
"place": 26,
"score": 200,
"local_id": 2
},
{
"name": "Ashley",
"place": 27,
"score": 193
}
{
"name": "Norman",
"place": 36,
"score": 103
},
{
"name": "Jack",
"place": 37,
"score": 100,
"local_id": 1
},
{
"name": "Chris",
"place": 38,
"score": 95
}
]
}
Every field except local_id and as I said place is stored in DB. I can't figure out the right sql query to do such select. Please help.

lodash filter array using query array

How can I filter an array of objects below using lodash? Here is my query
var query = { "body": ["Hatchback", "Sedan"] };
var objects = [{
"make": "BMW",
"model": "i3",
"maxRange": 81,
"price": "42,400",
"body": "Hatchback"
}, {
"make": "Chevrolet",
"model": "Spark EV",
"maxRange": 82,
"price": "25,120",
"body": "Hatchback"
}, {
"make": "Kia",
"model": "Soul EV",
"maxRange": 90,
"price": "31,950",
"body": "Wagon"
}, {
"make": "Tesla",
"model": "Model S",
"maxRange": 303.2,
"price": "75,000",
"body": "Sedan"
}, {
"make": "Tesla",
"model": "Model X",
"maxRange": 257,
"price": "83,000",
"body": "SUV"
}]
I tried to use _matches but it doesn't seem to match arrays. Here is my attempt
_.filter(objects, _.matches(query))
Ummm, I dont know about how to do with lodash but we can certainly do with vanillaJS in just two lines of code though.
var query = { "body": ["Hatchback", "Sedan"] };
var filteredObjArray = objects.filter(obj => query.body.includes(obj.body)))
Hope that helps :).
You can use JS .filter with .every to check multiple properties. If a query property is an array use .include to compare, if not make a simple comparison:
function multipleFilter(arr, query) {
var queryKeys = Object.keys(query); // create an array of the keys in the query object
return arr.filter(function(item) {
return queryKeys.every(function(key) { // use .every on the keys so if one fails, the item is filtered out
var keyData = item[key]; // get the data of the key from the item
var keyQuery = query[key]; // get the query from query object
return Array.isArray(keyQuery) ? keyQuery.includes(keyData) : keyQuery === keyData; // if the query is an array use include, if not use comparison
});
});
}
var objects = [{
"make": "BMW",
"model": "i3",
"maxRange": 81,
"price": "42,400",
"body": "Hatchback"
}, {
"make": "Chevrolet",
"model": "Spark EV",
"maxRange": 82,
"price": "25,120",
"body": "Hatchback"
}, {
"make": "Kia",
"model": "Soul EV",
"maxRange": 90,
"price": "31,950",
"body": "Wagon"
}, {
"make": "Tesla",
"model": "Model S",
"maxRange": 303.2,
"price": "75,000",
"body": "Sedan"
}, {
"make": "Tesla",
"model": "Model X",
"maxRange": 257,
"price": "83,000",
"body": "SUV"
}];
var query1 = {
"body": ["Hatchback", "Sedan"]
};
var query2 = {
"body": ["Hatchback", "Sedan"],
make: "BMW"
};
console.log('query1', multipleFilter(objects, query1));
console.log('query2', multipleFilter(objects, query2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>