I am trying to automate some API endpoints, but the JSON response is an array of data. How can I assert a specific user with all his data inside that JSON array?
I am trying with:
assert {
"user": "test1",
"userName": "John Berner",
"userid": "1"
} in response.json()
The JSON response is:
{
"data": [
{
"user": "test1",
"userName": "John Berner",
"userid": "1"
},
{
"user": "test2",
"userName": "Nick Morris",
"userid": "2"
}
],
"metadata": {
"current_page": 1,
"pages": 1,
"per_page": 100,
"total": 2
}
}
Please try like this:
You can use loop over the data within any to perform this check.
contents = json.loads(apiresponse_data)
assert any(i['user'] == 'test1' for i in contents['data'])
If all the fields are in the response are part of your user_info you can do what you are thinking of doing -
# response = json.loads(api_response_data)
response = {
"data": [
{
"user": "test1",
"userName": "John Berner",
"userid": "1"
},
{
"user": "test2",
"userName": "Nick Morris",
"userid": "2"
}
],
"metadata": {
"current_page": 1,
"pages": 1,
"per_page": 100,
"total": 2
}
}
user_info = {
"user": "test1",
"userName": "John Berner",
"userid": "1"
}
assert user_info in response['data']
Above doesn't raise AssertionError because the user_info is there in the response['data']
You can also use following if you have decoded the json response already -
assert {
"user": "test1",
"userName": "John Berner",
"userid": "1"
} in response['data']
Related
This is data JSON :
{ "activities": [ { "id": 1, "title": "likes your app x", "actor": { "type": "user", "id": 3 }, "verbs": [ "post" ], "object": { "type": "comment", "id": 1, "content": "Hello." }, "object": { "type": "app", "id": 1 } } ] }
I want the JSON object to table like this
hi I'm pretty new at coding and I was trying to create a program in python that reads and save in another file the data inside a json file (not everything, just what I want). I googled how to parse data but there's something I don't understand.
that's a part of the json file:
`
{
"profileRevision": 548789,
"profileId": "campaign",
"profileChangesBaseRevision": 548789,
"profileChanges": [
{
"changeType": "fullProfileUpdate",
"profile": {
"_id": "2da4f079f8984cc48e84fc99dace495d",
"created": "2018-03-29T11:02:15.190Z",
"updated": "2022-10-31T17:34:43.284Z",
"rvn": 548789,
"wipeNumber": 9,
"accountId": "63881e614ef543b2932c70fed1196f34",
"profileId": "campaign",
"version": "refund_teddy_perks_september_2022",
"items": {
"8ec8f13f-6bf6-4933-a7db-43767a055e66": {
"templateId": "Quest:heroquest_loadout_constructor_2",
"attributes": {
"quest_state": "Claimed",
"creation_time": "min",
"last_state_change_time": "2019-05-18T16:09:12.750Z",
"completion_complete_pve03_diff26_loadout_constructor": 300,
"level": -1,
"item_seen": true,
"sent_new_notification": true,
"quest_rarity": "uncommon",
"xp_reward_scalar": 1
},
"quantity": 1
},
"6940c71b-c74b-4581-9f1e-c0a87e246884": {
"templateId": "Worker:workerbasic_sr_t01",
"attributes": {
"gender": "2",
"personality": "Homebase.Worker.Personality.IsDreamer",
"level": 1,
"item_seen": true,
"squad_slot_idx": -1,
"portrait": "WorkerPortrait:IconDef-WorkerPortrait-Dreamer-F02",
"building_slot_used": -1,
"set_bonus": "Homebase.Worker.SetBonus.IsMeleeDamageLow"
}
}
}
]
}
`
I can access profileChanges. I wrote this to create another json file with only the profileChanges things:
`
myjsonfile= open("file.json",'r')
jsondata=myjsonfile.read()
obj=json.loads(jsondata)
ciso=obj['profileChanges']
for i in ciso:
print(i)
with open("file2", "w") as outfile:
json.dump( ciso, outfile, indent=1)
the issue I have is that I can't access "profile" (inside profileChanges) in the same way by parsing the new file and I have no idea on how to do it
Access to JSON or dict element is realized by list indexes, please look at below example:
a = [
{
"friends": [
{
"id": 0,
"name": "Reba May"
}
],
"greeting": "Hello, Doris Gallagher! You have 2 unread messages.",
"favoriteFruit": "strawberry"
},
]
b = a['friends']['id] # b = 0
I've added a couple of closing braces to make your snippet valid json:
s = '''{
"profileRevision": 548789,
"profileId": "campaign",
"profileChangesBaseRevision": 548789,
"profileChanges": [
{
"changeType": "fullProfileUpdate",
"profile": {
"_id": "2da4f079f8984cc48e84fc99dace495d",
"created": "2018-03-29T11:02:15.190Z",
"updated": "2022-10-31T17:34:43.284Z",
"rvn": 548789,
"wipeNumber": 9,
"accountId": "63881e614ef543b2932c70fed1196f34",
"profileId": "campaign",
"version": "refund_teddy_perks_september_2022",
"items": {
"8ec8f13f-6bf6-4933-a7db-43767a055e66": {
"templateId": "Quest:heroquest_loadout_constructor_2",
"attributes": {
"quest_state": "Claimed",
"creation_time": "min",
"last_state_change_time": "2019-05-18T16:09:12.750Z",
"completion_complete_pve03_diff26_loadout_constructor": 300,
"level": -1,
"item_seen": true,
"sent_new_notification": true,
"quest_rarity": "uncommon",
"xp_reward_scalar": 1
},
"quantity": 1
},
"6940c71b-c74b-4581-9f1e-c0a87e246884": {
"templateId": "Worker:workerbasic_sr_t01",
"attributes": {
"gender": "2",
"personality": "Homebase.Worker.Personality.IsDreamer",
"level": 1,
"item_seen": true,
"squad_slot_idx": -1,
"portrait": "WorkerPortrait:IconDef-WorkerPortrait-Dreamer-F02",
"building_slot_used": -1,
"set_bonus": "Homebase.Worker.SetBonus.IsMeleeDamageLow"
}
}
}
}
}
]
}
'''
d = json.loads(s)
print(d['profileChanges'][0]['profile']['version'])
This prints refund_teddy_perks_september_2022
Explanation:
d is a dict
d['profileChanges'] is a list of dicts
d['profileChanges'][0] is the first dict in the list
d['profileChanges'][0]['profile'] is a dict
d['profileChanges'][0]['profile']['version'] is the value of version key in the profile dict in the first entry of the profileChanges list.
Can't solve problem with POST and PUT request in strapi.io. My Relation is 1 to many (a ticket can have 1 category, a category can have many tickets).
GET request looks like this:
{
"data": {
"id": 1,
"attributes": {
"first_name": "Alex",
"last_name": "Porter",
"phone": "+74955978965",
"company": "Test",
"entry_time": null,
"entered": false,
"email": "test#test.com",
"count_entry": 0,
"createdAt": "2022-05-06T10:21:22.753Z",
"updatedAt": "2022-05-20T11:43:57.707Z",
"publishedAt": "2022-05-06T10:21:23.680Z",
"photo": {
"data": null
},
"category": {
"data": {
"id": 1,
"attributes": {
"name": "Junior",
"createdAt": "2022-05-20T11:36:46.360Z",
"updatedAt": "2022-05-20T11:37:17.517Z",
"publishedAt": "2022-05-20T11:37:17.516Z"
}
}
}
}
},
"meta": {}
}
This is what my function looks like with a PUT request:
def edit_member(self, member_id, first_name, last_name, phone, category):
url = config.SERVER + f'api/members/{member_id}?populate=%2A'
payload = {
'data': {
"attributes": {
"first_name": first_name,
"last_name": last_name,
"phone": phone,
},
"category": {
"data": {
"attributes": {
"name": category
}
}
}
}
}
headers = {
'Authorization': f'Bearer {config.TOKEN}',
'Content-Type': 'application/json'
}
requests.request("PUT", url, headers=headers, json=payload)
As a result, the data appears on the strapi, but the relation is lost (remains empty). Tell me, please, where to look?
Thank you in advance.
I'm quite new to Python and was wondering if there was a good way to create a new list of unduplicated users.
My problem is that I have something like this
[
{
"userId": "987654321",
"method": "CARD",
"lastDigits": "1234",
"type": "mc",
"first_name": "Leroy",
"last_name": "Jenkins",
"exp": "01/23"
},
{
"userId": "987654321",
"method": "PAYPAL",
"first_name": "Leroy",
"last_name": "Jenkins"
},
{
"userId": "123456789",
"method": "CARD",
"lastDigits": "4567",
"type": "visa",
"first_name": "Joe",
"last_name": "Bloggs",
"exp": "01/25"
},
{
"userId": "46513498000",
"method": "PAYPAL",
"first_name": "Betty",
"last_name": "White"
}
]
Basically I need to match when the userId has matched and keep the object when "method": "CARD"instead of PAYPAL then reconstruct essentially the same list again but minus the duplicate userId's when the user has both CARD and PAYPAL
::EDIT::
User can just have PAYPAL. and if it does just have PAYPAL, just return that
example output needed
[
{
"userId": "987654321",
"method": "CARD",
"lastDigits": "1234",
"type": "mc",
"first_name": "Leroy",
"last_name": "Jenkins",
"exp": "01/23"
},
{
"userId": "123456789",
"method": "CARD",
"lastDigits": "4567",
"type": "visa",
"first_name": "Joe",
"last_name": "Bloggs",
"exp": "01/25"
},
{
"userId": "46513498000",
"method": "PAYPAL",
"first_name": "Betty",
"last_name": "White"
}
]
This will perfectly work for your. Try and check it
mylist=[
{
"userId": "987654321",
"method": "CARD",
"lastDigits": "1234",
"type": "mc",
"first_name": "Leroy",
"last_name": "Jenkins",
"exp": "01/23"
},
{
"userId": "987654321",
"method": "PAYPAL",
"first_name": "Leroy",
"last_name": "Jenkins"
},
{
"userId": "123456789",
"method": "CARD",
"lastDigits": "4567",
"type": "visa",
"first_name": "Joe",
"last_name": "Bloggs",
"exp": "01/25"
},
{
"userId": "46513498000",
"method": "PAYPAL",
"first_name": "Betty",
"last_name": "White"
}
]
temp_list=[]
temp_id=[]
for x in mylist:
if int(x['userId']) not in temp_id:
temp_list.append(x)
temp_id.append(int(x["userId"]))
print(temp_list)
If I don't misunderstood your question then simple filtering will do the trick for you,
user_ids = []
final_users = []
for user in users:
user_ids.append(int(user['userId']))
if user['userId'] not in user_ids and user['method'] != 'PAYPAL':
final_users.append(user)
print(final_users)
Working Code: https://rextester.com/COBGVU63922
users = {}
for d in user_list:
uid = d["userId"]
# If user id not in users, we add it
if uid not in users:
users[uid] = d
# Otherwise we check if the already recorded method was "PAYPAL",
# if so we overwrite it.
elif users[uid]["method"] == "PAYPAL":
users[uid] = d
# To convert dict we just created back to list:
user_list = list(users.values())
Use defaultdict:
from collections import defaultdict
newdata = defaultdict(dict)
for item in data:
userid = newdata[item['userId']]
if userid == {} and item['method'] == 'CARD':
userid.update(item)
Output:
# newdata = list(newdata.values())
>>> newdata
[{'userId': '987654321',
'method': 'CARD',
'lastDigits': '1234',
'type': 'mc',
'first_name': 'Leroy',
'last_name': 'Jenkins',
'exp': '01/23'},
{'userId': '123456789',
'method': 'CARD',
'lastDigits': '4567',
'type': 'visa',
'first_name': 'Joe',
'last_name': 'Bloggs',
'exp': '01/25'}]
I want to convert my response in json format but it is converting it into string.
Response expected
{
"recipient_id": "default",
"data": [{
"Name": "John",
"status": "To Be Processed",
"LastUpdatedDate": "2013-05-31 08:40:55.0"
}, {
"Name": "Paul",
"status": "To Be Processed",
"LastUpdatedDate": "2013-06-02 16:03:00.0"
}] };
Response getting
{
"recipient_id": "default",
"data": ""[{
"Name": "John",
"status": "To Be Processed",
"LastUpdatedDate": "2013-05-31 08:40:55.0"
}, {
"Name": "Paul",
"status": "To Be Processed",
"LastUpdatedDate": "2013-06-02 16:03:00.0"
}]""
};
i am using dispatcher.utter_message to send response.