autofilling a dict python 2.x - python-2.7

I'm quite new to Python and programming in general, so apologies if this is quite basic or has been asked and answered before. Here is a sample of the data I'm working with:
{
"homeTeam": {
"formation": [
"4",
"4",
"2"
],
"lineupsSorted": [
{
"player": {
"name": "Scott P. Brown",
"slug": "scott-p-brown",
"shortName": "S. P. Brown",
"id": 19889,
"hasImage": true
},
"position": 1,
"shirtNumber": 1,
"substitute": false,
"positionName": "Goalkeeper",
"positionNameshort": "G",
"captain": false
},
{
"player": {
"name": "Carl Winchester",
"slug": "carl-winchester",
"shortName": "C. Winchester",
"id": 110785,
"hasImage": true
},
"position": 2,
"shirtNumber": 27,
"substitute": false,
"positionName": "Midfielder",
"positionNameshort": "M",
"captain": false
},
I am looking to automate populating defined names as I have done manually here:
hometeamPositions =['Goalkeeper','Midfielder','Defender','Defender','Defender','Midfielder','Midfielder','Midfielder','Midfielder','Forward','Forward','Goalkeeper','Defender','Defender','Midfielder','Midfielder','Forward','Forward']
hometeamPlayers = ['S. P. Brown','C. Winchester','M. Onariase','W.
Boyle','J. Cranston','H. Pell','J. Rowe','K. Storer','B. Waters','D.
Wright','D. Holman','R. Lovett','J. Barthram','T. Plavotic','J.
Munns','L. Davis','K. Wootton','J. Dayton']
As I will be repeating this process many hundreds of times with different data (same structure) I was wondering if anyone could give me some tips on automatically building these ranges?
Thanks,
Peter

I'm not sure I understood what is the problem you are trying to solve but I'll try to help.
Assuming you have a dictionary team_dict and you want to create 2 list: hometeamPositions and hometeamPlayers you can use the following code:
hometeamPlayers = []
hometeamPositions = []
for player_dict in teams_dict['homeTeam']['lineupsSorted']:
hometeamPlayers.append(player_dict['player']['shortName'])
hometeamPositions.append(player_dict['positionName'])
The output on your example will be:
hometeamPlayers = ['S. P. Brown', 'C. Winchester']
hometeamPositions = ['Goalkeeper', 'Midfielder']

Related

How to use match as with Regular Expression in Mongodb with in Aggregate switch case?

Here what i did.
Inside $AddFields
{
ClientStatus:{
$switch: {
branches: [
{ case: {
$eq:
[
"$CaseClientStatus",
/In Progress/i
]},
then:'In Progress'
},
{ case: {
$eq:
[
"$CaseClientStatus",
{regex:/Cancelled/i}
],
},then:'Cancelled'},
{ case: {$eq:['$CaseClientStatus','Complete - All Results Clear']}, then:'Complete'},
{ case: {$eq:['$CaseClientStatus','Case on Hold']}, then:'Case on Hold'}
],
default: 'Other'
}}
}
but with this my ClientStatus is showing only Complete,Other,Case On Hold not the one with specified with regex. alghough field contains those words.
here is the one of the doc
{
"CandidateName": "Bruce Consumer",
"_id": "61b30daeaa237672bb7a17cc",
"CaseClientStatus": "Background Check Case In Progress",
"TAT": "N/A",
"CaseCloseDate": null,
"FormationAutomationStatus": "Automated",
"MethodOfDataSupply": "Automated",
"Status": "Background Case In Progress",
"CreatedDate": "2021-12-10T08:19:58.389Z",
"OrderId": "Ord3954",
"PONumber": "",
"Position": "",
"FacilityCode": "",
"IsCaseClose": false,
"Requester": "Shah Shah",
"ReportErrorList": 0
}
Assuming you are on version 4.2 or higher (and you should be because 4.2 came out almost 2 years ago) then the $regexFind function gives you what you need. Prior to 4.2, regex was only available in a $match operator, not in complex agg expressions. Your attempt above is admirable but the // regex syntax is not doing what you think it should be doing. Notably, {regex:/Cancelled/i} is simply creating a new object with key regex and string value /Cancelled/i (including the slashes) which clearly will not equal anything in $CaseClientStatus. Here is a solution:
ClientStatus:{
$switch: {
branches: [
{ case: {
$ne: [null, {$regexFind: {input: "$CaseClientStatus", regex: /In Progress/i}}]
}, then:'In Progress'},
{ case: {
$ne: [null, {$regexFind: {input: "$CaseClientStatus", regex: /Cancelled/i}}]
},then:'Cancelled'},
{ case: {$eq:['$CaseClientStatus','Complete - All Results Clear']}, then:'Complete'},
{ case: {$eq:['$CaseClientStatus','Case on Hold']}, then:'Case on Hold'}
],
default: 'Other'
}}
It looks like you are trying to take a somewhat free-form status "description" field and create a strong enumerated status from it. I would recommend that your $ClientStatus output be more code-ish e.g. IN_PROGRESS, COMPLETE, CXL etc. Eliminate case and certainly whitespace.

Gatling : regex to get a specific value from a JSON

I have this JSON Object coming from an HTML.
{
"isCompany": false,
"accommodations": [
{
"id": "00000000031000006435",
"isChecked": false,
"name": "Théo",
"addressLine1": "Rue des patriotes 40 Y",
"addressLine2": "1050 Ixelles",
"nightsDeclared": 5,
"schoolNightsDeclared": 3,
"schoolNightsAttached": 0,
"taxableNights": 2.0,
"totalPayment": 0.0,
"isInProgress": true,
"isLate": false,
"isPayed": "false",
"deadline": "2021-12-31",
"initialAmount": 0.0,
"remainingAmount": 0.0
},
{
"id": "00000000031000006438",
"isChecked": false,
"name": "Théo",
"addressLine1": "Rue des Gens 45 B",
"addressLine2": "1040 Etterbeek",
"nightsDeclared": 5,
"schoolNightsDeclared": 3,
"schoolNightsAttached": 0,
"taxableNights": 2.0,
"totalPayment": 0.0,
"isInProgress": true,
"isLate": false,
"isPayed": "false",
"deadline": "2021-12-31",
"initialAmount": 0.0,
"remainingAmount": 0.0
}
]
}
I know that in Gatling, it is possible to get the accommodation id by writing this regex :
check(regex(""""accommodations":\[\{"id":"(.*?)"""").saveAs("accommodationId"))
Now my question is, what is the regex that gets the "isInProgress"?
Don't!
Using regex in this specific case could result in your code breaking on slight input changes and will result in unreadable code.
Instead deserialize and access as a dictionary?
[a['id'] for a in json.loads(json_string)['accommodations']]
Also, have you tried to simply replace id with the name of the field you want?
If you insist on using regex for this, check out online regex sites like regex101.com, regexr.com, regextester.com etc. (search for "online regex test") and try to solve this yourself. If your code does not work, ask a question again.
Ok, you have this in your regex
"id":"(.*?)"
You need just change to expected key name as isInProgress or any another. Also pay attention on " around (.*?) - since the value for id a string, they are needed, but value in isInProgress with another type.

Secondary Index not working for Database using #key

I should get the DynamoDb id for Justin. The call doesn't seem to fail. If i console.log(returned) i get an [object Object]. When i try to get to the returned.data.getIdFromUserName.id or returned.data.getIdFromUserName.email (anything else in the table) i get undefined. What am i missing?
Returned data:
{
"data": {
"getIdFromUserName": {
"items": [
{
"id": "3a5a2ks4-f137-41e2-a604-594e0c52a298",
"userName": "Justin",
"firstname": "null",
"weblink": "#JustinTimberlake",
"email": "iuiubiwewe#hotmail.com",
"mobileNum": "+0123456789",
"profilePicURI": "null",
"listOfVideosSeen": null,
"userDescription": "I wanna rock your body, please stay",
"isBlocked": false,
"GridPairs": null
}
],
"nextToken": null
}
}
}
I'd suggest getting a better idea of what console.log(returned) is printing.
Try console.log(JSON.stringify(returned, null, 2)) to inspect what is being returned.
EDIT: The data you're working with looks like this:
{
"data": {
"getIdFromUserName": {
"items": [
{
"id": "3a5a2ks4-f137-41e2-a604-594e0c52a298",
"userName": "Justin",
"firstname": "null",
"weblink": "#JustinTimberlake",
"email": "iuiubiwewe#hotmail.com",
"mobileNum": "+0123456789",
"profilePicURI": "null",
"listOfVideosSeen": null,
"userDescription": "I wanna rock your body, please stay",
"isBlocked": false,
"GridPairs": null
}
],
"nextToken": null
}
}
}
Pay close attention to the structure of that response. Both data and getIdFromUserName are maps. The content of data.getIdFromUserName is an array named items. Therefore, data.getIdFromUserName.items is an array containing the results of your query. You'll need to iterate over that array to get the data you are looking for.
For example, data.getIdFromUserName.items[0].id would be 3a5a2ks4-f137-41e2-a604-594e0c52a298
To access the email it would be data.getIdFromUserName.items[0].email.

Search numbers between quotation marks and remove it (VS Code)

I've a really big .json file with this structure:
[
"9": {
"id": 9,
"chapter": 4
},
"4": {
"id": 82,
"chapter": 32
},
]
I want to remove every quotation marks before the brackets. The file should looking like this:
[
{
"id": 9,
"chapter": 4
},
{
"id": 82,
"chapter": 32
},
]
I found a similar question here, but the result isn't that what I want.
this step will remove keys; what are looking for( assuming no nested objects ) :
"\d+":\s*{ replace with '{'
this will remove latest ,if exist and turn last } to ]
},?\s*}$ replace with '}]'
optional step: this will remove latest ,if exist
},?\s*]$ replace with '}]'
check code snippet below for working example from your input to a valid json:
copy the pattern between // and paste it to vs-code find bar; (e.g. /},?\s*]$/ will be },?\s*]$) to be used in VSCode and the likewise for the replace
const input = `[
"9": {
"id": 9,
"chapter": 4
},
"4": {
"id": 82,
"chapter": 32
},
]`
const step1Find = /"\d+":\s*{/g;const step1Replace = '{'
//not needed anymore
//const step2Find = /^{/;const step2Replace = '['
//removing lastest comma if exists
const step3Find = /},?\s*]$/;const step3Replace = '}]'
let stringObject = input
.replace(step1Find,step1Replace)
.replace(step3Find,step3Replace)
console.log(JSON.parse(stringObject))

Creating a json database with user input

I need to create my .json array to look like this:
{
"airports": [{
"address": "Horley, Gatwick RH6 0NP, UK",
"city": "London",
"shortVersion": "LGW"
},
{
"address": "Marupe, LV-1053",
"city": "Riga",
"shortVersion": "RIX"
}
]
}
But I have it looking right now like this:
{
"airports": {
"(LGW)": {
"address": "Horley, Gatwick RH6 0NP, UK",
"city": "London",
"shortVersion": "(LGW)"
},
"(RIX)": {
"address": "Marupe, LV-1053",
"city": "Riga",
"shortVersion": "(RIX)"
}
}
}
The code I have for user input right now is this:
airports["airports"][inputShortVersion]["shortVersion"] = inputShortVersion;
airports["airports"][inputShortVersion]["city"] = inputCity;
airports["airports"][inputShortVersion]["address"] = inputAddress;
I've searched for a whole day on how to do this, but closest I got to was where it does create the above array but after input it overwrites the last airport data.
I'm using nlohmann json library.
You have a sequence container in your desired output, but associative container in your code.
Try something like
json inputAirport;
inputAirport["shortVersion"] = inputShortVersion;
inputAirport["city"] = inputCity;
inputAirport["address"] = inputAddress;
airports["airports"].push_back(inputAirport);
Apparently, you are creating a json object instead of a json array. To get an array, you could try along the lines of the following:
airports["airports"] = nlohmann::json::array()
new_airport = nlohmann::json::object()
new_airport["shortVersion"] = inputShortVersion;
new_airport["city"] = inputCity;
new_airport["address"] = inputAddress;
airports["airports"].emplace_back(new_airport);
This can be written shorter with braced initalizer lists at the cost of readability:
airports["airports"] = nlohmann::json::array()
airports["airports"].emplace_back(
{
{"shortVersion", inputShortVersion},
{"city", inputCity},
{"address", inputAddress}
});