I have list of dictionary objects with date and name and status.
elements = [
{
"PersonId": 301178,
"Wwid": "10692133",
"FullNm": "abc",
"CompletionDt": "2015-04-29",
"status": "Complete",
},
{
"PersonId": 301178,
"Wwid": "10692133",
"FullNm": "abc",
"CompletionDt": "2019-07-30",
"status": "complete",
},
{
"PersonId": 301178,
"Wwid": "10692133",
"FullNm": "abc",
"CompletionDt": "2016-08-01",
"status": "Inclomplete",
},
{
"PersonId": 301178,
"Wwid": "10692133",
"FullNm": "abc",
"CompletionDt": "2017-04-10",
"status": "Completed",
},
]
In this dictionary how to pick the latest dated object using python?
In the above example
result= {
"PersonId": 301178,
"Wwid": "10692133",
"FullNm": "abc",
"CompletionDt": "2019-07-30",
"status" : "complete"
}
from datetime import datetime
result = sorted(
elements, key=lambda x: datetime.strptime(x["CompletionDt"], "%Y-%m-%d")
)[-1]
or you can try python built-in max.
result = max(elements, key=lambda x: datetime.strptime(x["CompletionDt"], "%Y-%m-%d"))
Output:
{'PersonId': 301178, 'Wwid': '10692133', 'FullNm': 'abc', 'CompletionDt': '2019-07-30', 'status': 'complete'}
Here I am going to assume that your objects' ID is getting larger as time goes on (the later an object is created, the larger the ID) as comparing DateTime objects will be a pain - or unnecessary.
qs = Person.objects.order_by('-id')[0]
Basically you sort it by reversing ID order (largest --> smallest) and then retrieve the first item, which will be the latest created object in the queryset
if my assumption above stands.
result = max(x['CompletionDt'] for x in myList)
Related
I am working in MS Power Automate (Flow) and I want to filter a JSON array by a string to retrieve the value...
here is a subset of my JSON Data (this data has been extracted from a SharePoint list by a Flow Get Items step):
[
{
"#odata.etag": "\"2\"",
"ItemInternalId": "1",
"ID": 1,
"Setting1": {
"#odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
"Id": 0,
"Value": "Email Addresses"
},
"Setting1#Id": 0,
"Setting2": {
"#odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
"Id": 0,
"Value": "Retail Marketing Team Email"
},
"Setting2#Id": 0,
"Value1": "person1#company.co.uk; person2#company.co.uk; "
},
{
"#odata.etag": "\"2\"",
"ItemInternalId": "2",
"ID": 2,
"Setting1": {
"#odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
"Id": 0,
"Value": "Email Addresses"
},
"Setting1#Id": 0,
"Setting2": {
"#odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
"Id": 1,
"Value": "Social Media Email"
},
"Setting2#Id": 1,
"Value1": "paidsocial#company.co.uk; person3#company.co.uk; person4#company.co.uk;"
},
....
]
I need to filter that on the field Setting2 = "search string", and return Value1 by matching a string
So, for Setting2 I would use 'Retail Marketing Team Email' and extract the value of the Value1 field which is '*person1#company.co.uk; person2#company.co.uk; *'
Now, with $..['Value1'] I can get all of the Value1 values, and with filtering I should be able to retrieve a specific Value1 element...
I have tried this:
$.[?(#.Setting2 == 'Retail Marketing Team Email')]['Value1']
and
$..['Setting2'].['Value' == 'Retail Marketing Team Email']?['Value']
and several other variations but never seem to get any data back, or OI get a JSON Parse error
what is the right way to go about this?
I have captured two sets of values by using JSON extractor in JMeter which I want to concatenate. Let me give you an example below for the format which I want to use.
The following are the two sets of captured values:
Set 1: [V2520 V2522 V2521 V2500 V2500]
Set 2: [PL PL PL NP NP]
So from the above sets, I am looking for the something like the following value, because the body which I have to send in a subsequent call contains the combination of these 2 values:
Answer: ["V2520PL", "V2522PL", "V2521PL", "V2500NP", "V2500NP"]
Can you please help me how to solve this in JMeter using Groovy?
This is the JSON I have:
{ "body": {
"responseObject": [
{
"benefitInfo": [
{
"procedureCode": "V2520",
"modifier": "PL",
"usage": "Dress",
"authorizationID": null,
"description": "ContactLensDisposable",
"id": "96",
"coPayAmount": "25"
},
{
"procedureCode": "V2522",
"modifier": "PL",
"usage": "Dress",
"authorizationID": null,
"description": "ContactLensDisposableBifocal",
"id": "98",
"coPayAmount": "25"
},
{
"procedureCode": "V2521",
"modifier": "PL",
"usage": "Dress",
"authorizationID": null,
"description": "ContactLensDisposableToric",
"id": "97",
"coPayAmount": "25"
},
{
"procedureCode": "V2500",
"modifier": "NP",
"usage": "Dress",
"authorizationID": null,
"description": "ContactLens (Non Plan)",
"id": "89",
"coPayAmount": "0"
},
{
"procedureCode": "V2500",
"modifier": "NP",
"usage": "Dress",
"authorizationID": null,
"description": "ContactLensConventional (Non Plan)",
"id": "157",
"coPayAmount": "0"
}
]
}
]}}
An easy way to do this is to combine them as you collect the values from the JSON when you parse it.
def json = new groovy.json.JsonSlurper().parseText(text)
def answer = json.body.responseObject[0].benefitInfo.collect { it.procedureCode + it.modifier }
assert answer == ["V2520PL", "V2522PL", "V2521PL", "V2500NP", "V2500NP"]
Another method would be to use transpose() and join():
def r = new groovy.json.JsonSlurper().parseText(text).body.responseObject.benefitInfo[0]
def answer = [r.procedureCode, r.modifier].transpose()*.join()
assert answer == ["V2520PL", "V2522PL", "V2521PL", "V2500NP", "V2500NP"]
Add JSR223 PostProcessor as a child of the request which returns the above JSON
Put the following code into "Script" area:
def answer = []
def benefitInfos = com.jayway.jsonpath.JsonPath.read(prev.getResponseDataAsString(), '$..benefitInfo')
benefitInfos.each { benefitInfo ->
benefitInfo.each { entry ->
answer.add(entry.get('procedureCode') + entry.get('modifier'))
}
}
vars.put('answer', new groovy.json.JsonBuilder(answer).toPrettyString())
That's it, you will be able to access generated value as ${answer} where required:
References:
Jayway JsonPath
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
In my render() method i need to parse nested json objects. See the portion of render and json structure below.
I access Last Name with {params.name_last}.
How will i access items under team, like team.name_first
render() {
let { params } = this.props.navigation.state
<Text>{params.name_last}</Text>
}
[
{
"id": 1,
"name_first": "Name first 1",
"name_middle": "",
"name_last": "Name last 1",
"name_suffix": "",
"phone": "888-8888",
"fax": "888-8888",
"updated_at": "2015-11-02T21:42:42.000Z",
"team": [
{
"id": 16,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 28,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 29,
"name_first": "aaa ",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
}
]
}
]
Since team is an array, you need to either access a specific entry in the array, or iterate over the entire thing.
To reach a specific property in the nested array entry (assuming you want the object at index i):
params.team[i].name_first
To create an array of first names:
params.team.map(x => x.name_first)
I am trying to insert the Large JSON document in the Couchbase. I have inserted the document like below.
Bucket bucket = cluster.openBucket("default");
String jsondoc = "{{
"exams": {
"exam1": {
"year": {
"math": {
"questions": [
{
"question_text": "first question",
"options": [
"option1",
"option2",
"option3",
"option4",
"option5"
],
"answer": 1,
"explaination": "explain the answer"
},
{
"question_text": "second question",
"options": [
"option1",
"option2",
"option3",
"option4",
"option5"
],
"answer": 1,
"explaination": "explain the answer"
},
{
"question_text": "third question",
"options": [
"option1",
"option2",
"option3",
"option4",
"option5"
],
"answer": 1,
"explaination": "explain the answer"
}
]
},
"english": {same structure as above}
},
"1961": {}
},
"exam2": {},
"exam3": {},
"exam4": {}
}
}}";
JSONObject jsonObj = new JSONObject();
jsonObj.put("examinfo", jsondoc);
bucket.upsert(JSONDocument.create("exam", jsonObj));
After Inserting the document like above, I want to retrieve individual nested nodes(ex: questions) while fetching.
I have the following queries:
1) Can I Insert the document by using traditional approach:
String query = "upsert into default(KEY, VALUE) values(jsondoc)";
statement.executeUpdateQuery(query);
or Should I need to insert the above nested nodes individually in each JSONObject to fetch the nested nodes properly?
2) How to use N1QLQueryResult to fetch the each json document as a row only to fetch required json information
Which version of Couchbase are you using? There is a sub-doc API in version 4.5 that is for operating on parts of a JSON document:
http://developer.couchbase.com/documentation/server/4.5-dp/sub-doc-api.html
For your second question, you may want to look into the UNNEST N1QL operator.
I'm using the next Json
{
"ID": 8,
"MenuItems": [
{
"ID": 38,
"Name": "Home",
"URL": "{\"PageLayout\":\"Home\",\"Icon\":\"home\"}",
"Culture": "en",
"Children": null
},
{
"ID": 534,
"Name": "GUIDE ",
"URL": "{''PageLayout'':''Page A'', ''Icon'':''A''}",
"MenuType": 1,
"PageID": 0,
"Culture": "en",
"Children": [
{
"ID": 6,
"Name": "Form A",
"URL": "[''Type'':''Form A'',''Icon'':''Form'',''ItemID'':\"358\"]",
"Culture": "he",
"RuleID": 0
},
{
"ID": 60,
"Name": "Drama",
"URL": "[''Type'':''Form B'',''Icon'':''Form'',''ItemID'':\"3759\"]",
"Culture": "en",
"RuleID": 0
}
]
}
]
}
i'm using Groovy script in soapUI and i need to:
Assert the exitance of node that has the name GUIDE
Extract a list of all Itemsid
You can parse the JSON content using JsonSlurper and then work with the results like so:
import groovy.json.JsonSlurper
// Assuming your JSON is stored in "jsonString"
def jsonContent = new JsonSlurper().parseText(jsonString)
// Assert node exists with name GUIDE
assert(jsonContent.MenuItems.Name.contains("GUIDE"))
// Get list of ItemIDs
def itemList = jsonContent.MenuItems.Children.URL.ItemID[0].toList()
// List the items
itemList.each {log.info it}
Note that the above will fail given your current example, because of a few issues. Firstly, Name contains "GUIDE " (trailing space) rather than "GUIDE" (so you will need to adapt accordingly). Secondly, it is invalid JSON; the URL nodes have various erroneous characters.
On a side note, if you first need to retrieve your JSON from the response associated with a previous TestStep (say one called "SendMessage") within the existing testCase, this can be done as follows:
def jsonString = context.testCase.getTestStepByName("SendMessage").testRequest.response.getContentAsString()