Add an object to every json array in python - python

I'm trying to figure out how to add the same object to every array.
I'm requesting data from the server for the "first game". When I get it back, it doesn't include any data referencing the first game. So I need to edit it before I send it to my server to save.
I have a json request that looks like this:
{
'dateTime': '2022-07-01T01:00:00.000000',
'httpStatus': 'OK',
'message': 'SUCCESS',
'details': None,
'detailsList': [
{
'date': '2021-07-01T00:00:00',
'tcount': 0,
'first_name': 'Sam',
'last_name': 'Smith'
},
{
'user_reg_date': '2022-06-01T00:00:00',
'tcount': 0,
'first_name': 'Bob',
'last_name': 'Jones'
}]
}
I'm trying to figure out how to add an object to each json array (hope I'm saying that the right way) before I then send it to a mongodb.
In this example:
'game': 'first'
It would then look like this:
{
'dateTime': '2022-07-01T01:00:00.000000',
'httpStatus': 'OK',
'message': 'SUCCESS',
'details': None,
'detailsList': [
{
'date': '2021-07-01T00:00:00',
'tcount': 0,
'first_name': 'Sam',
'last_name': 'Smith',
'game': 'first'
},
{
'user_reg_date': '2022-06-01T00:00:00',
'tcount': 0,
'first_name': 'Bob',
'last_name': 'Jones',
'game': 'first'
}]
}
if there is a better way to do this, that would work as well.

Your asking something similar to this question. But want to loop through a JSON array in Python.
You are not trying to add an 'object' to json 'array'. You have a JSON object, of which there are object members (or more commonly, properties). You have an array as an object member of which you want to modify each object in the array to add a new property.
The code below is the above link with some modification to fit your needs. request_data is the JSON object you give in your example above. You need enumerate to know which index to edit.
for index, item in enumerate(request_data['detailsList']):
# Edit the array entry
item["game"] = 'first'
# Save it
request_data['detailsList'][index] = item

Related

Problem when saving json data into python list

I'm trying to get two attributes at the time from my json data and add them as an item on my python list. However, when trying to add those two: ['emailTypeDesc']['createdDate'] it throws an error. Could someone help with this? thanks in advance!
json:
{
'readOnly': False,
'senderDetails': {'firstName': 'John', 'lastName': 'Doe', 'emailAddress': 'johndoe#gmail.com', 'emailAddressId': 123456, 'personalId': 123, 'companyName': 'ACME‘},
'clientDetails': {'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe#gmail.com', 'emailAddressId': 654321, 'personalId': 456, 'companyName': 'Lorem Ipsum‘}},
'notesSection': {},
'emailList': [{'requestId': 12345667, 'emailId': 9876543211, 'emailType': 3, 'emailTypeDesc': 'Email-In', 'emailTitle': 'SampleTitle 1', 'createdDate': '15-May-2020 11:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe#gmail.com',}]},
{'requestId': 12345667, 'emailId': 14567775, 'emailType': 3, 'emailTypeDesc': 'Email-Out', 'emailTitle': 'SampleTitle 2', 'createdDate': '16-May-2020 16:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe#gmail.com',}]},
{'requestId': 12345667, 'emailId': 12345, 'emailType': 3, 'emailTypeDesc': 'Email-In', 'emailTitle': 'SampleTitle 3', 'createdDate': '17-May-2020 20:15:52', 'fromMailList': [{'firstName': 'Jane', 'lastName': 'Doe', 'emailAddress': 'janedoe#gmail.com',}]
}
python:
final_list = []
data = json.loads(r.text)
myId = [(data['emailList'][0]['requestId'])]
for each_req in myId:
final_list.append(each_req)
myEmailList = [mails['emailTypeDesc']['createdDate'] for mails in data['emailList']]
for each_requ in myEmailList:
final_list.append(each_requ)
return final_list
This error comes up when I run the above code:
TypeError: string indices must be integers
Desired output for final_list:
[12345667, 'Email-In', '15-May-2020 11:15:52', 'Email-Out', '16-May-2020 16:15:52', 'Email-In', '17-May-2020 20:15:52']
My problem is definetely in this line:
myEmailList = [mails['emailTypeDesc']['createdDate'] for mails in data['emailList']]
because when I run this without the second attribute ['createdDate'] it would work, but I need both attributes on my final_list:
myEmailList = [mails['emailTypeDesc'] for mails in data['emailList']]
I think you're misunderstanding the syntax. mails['emailTypeDesc']['createdDate'] is looking for the key 'createdDate' inside the object mails['emailTypeDesc'], but in fact they are two items at the same level.
Since mails['emailTypeDesc'] is a string, not a dictionary, you get the error you have quoted. It seems that you want to add the two items mails['emailTypeDesc'] and mails['createdDate'] to your list. I'm not sure if you'd rather join these together into a single string or create a sub-list or something else. Here's a sublist option.
myEmailList = [[mails['emailTypeDesc'], mails['createdDate']] for mails in data['emailList']]
Strings in JSON must be in double quotes, not single.
Edit: As well as names.

how to use nested dictionary in python?

I am trying to write some code with the Hunter.io API to automate some of my b2b email scraping. It's been a long time since I've written any code and I could use some input. I have a CSV file of Urls, and I want to call a function on each URL that outputs a dictionary like this:
`{'domain': 'fromthebachrow.com', 'webmail': False, 'pattern': '{f}{last}', 'organization': None, 'emails': [{'value': 'fbach#fromthebachrow.com', 'type': 'personal', 'confidence': 91, 'sources': [{'domain': 'fromthebachrow.com', 'uri': 'http://fromthebachrow.com/contact', 'extracted_on': '2017-07-01'}], 'first_name': None, 'last_name': None, 'position': None, 'linkedin': None, 'twitter': None, 'phone_number': None}]}`
for each URL I call my function on. I want my code to return just the email address for each key labeled 'value'.
Value is a key that is contained in a list that itself is an element of the directory my function outputs. I am able to access the output dictionary to grab the list that is keyed to 'emails', but I don't know how to access the dictionary contained in the list. I want my code to return the value in that dictionary that is keyed with 'value', and I want it to do so for all of my urls.
from pyhunyrt import PyHunter
import csv
file=open('urls.csv')
reader=cvs.reader (file)
urls=list(reader)
hunter=PyHunter('API Key')
for item in urls:
output=hunter.domain_search(item)
output['emails'`
which returns a list that looks like this for each item:
[{
'value': 'fbach#fromthebachrow.com',
'type': 'personal',
'confidence': 91,
'sources': [{
'domain': 'fromthebachrow.com',
'uri': 'http://fromthebachrow.com/contact',
'extracted_on': '2017-07-01'
}],
'first_name': None,
'last_name': None,
'position': None,
'linkedin': None,
'twitter': None,
'phone_number': None
}]
How do I grab the first dictionary in that list and then access the email paired with 'value' so that my output is just an email address for each url I input initially?
To grab the first dict (or any item) in a list, use list[0], then to grab a value of a key value use ["value"]. To combine it, you should use list[0]["value"]

Testing with Django: how to display all characters when using assertEqual with json object?

I'm testing django-rest-framework. When I POST some content in json format and want to test if it was posted correctly I try to get the object posted with
resp_get = self.client.get(self.url)
and test with assertEqual (json format):
self.assertEqual(
json.loads(resp_get.content.decode('utf8')),
[
{
'id': researcher.id,
'first_name': researcher.first_name,
'surname': researcher.surname,
'email': researcher.email,
'studies': [],
'nes_id': researcher.nes_id,
'owner': researcher.owner.username
}
]
)
As comparing results false, I get an AssertionError with following message
AssertionError: {'id': 1, 'first_name': 'João Maria', 'su[102 chars]ab1'} != [{'id': 1, 'first_name': 'João Maria', 's[104 chars]b1'}]
I'd like to know if is someway possible to get entire json object compared in both sides, as AssertionError returns the object compacted: su[102 chars]ab1, and s[104 chars]b1.
use assertDictEqual
self.assertDictEqual(item1, item2)

Trouble accessing a value from a dictionary

I have the following dictionary
Dict = {'Manu':{u'ID0020879.07': [{'ID': u'ID0020879.07', 'log': u'log-123-56', 'owner': [Manu], 'item': u'WRAITH', 'main_id': 5013L, 'status': u'noticed', 'serial': u'89980'}]}}
How can I access the serial from this dictionary?
I tried Dict['Manu']['serial'], But its not working as expected..
Guys any idea?
Your dictionary is very nested one.Try like this.
In [1]: Dict['Manu']['ID0020879.07'][0]['serial']
Out[1]: u'89980'
Here is the restructured dictionary.
{
'Manu': {
u'ID0020879.07': [{
'ID': u'ID0020879.07',
'log': u'log-123-56',
'owner': [Manu],
'item': u'WRAITH',
'main_id': 5013L,
'status': u'noticed',
'serial': u'89980'
}]
}
}
Now, you can see where the serial key is located more clearly (not under Manu)...
It is instead
Dict['Manu']['ID0020879.07'][0]['serial']
I suggest you fix that data source to not make ID0020879.07 a key of the data (because it is duplicated in the ID key of that object in the list).
Perhaps fix like so where the Manu key maps to a list of "accounts", each with an ID and other fields
{
'Manu': [{
'ID': u'ID0020879.07',
'log': u'log-123-56',
'owner': [Manu],
'item': u 'WRAITH',
'main_id': 5013L,
'status': u'noticed',
'serial': u'89980'
}]
}
And then you could do
Dict['Manu'][0]['serial']
Or loop the list to get all the serial keys
for item in Dict['Manu']:
print(item['serial'])

Accessing Data Nested in Dictionary in Array in Dictionary

I'm feeling stumped and looking for help. I'm trying to access data that lives inside of a dictionary that's inside of an array that is inside of a dictionary. See below:
{
'files': [
{
'type': 'diskDescriptor',
'name': '[VM] VM1/VM1.vmdk',
'key': 4,
'size': 0
},
{
'type': 'diskExtent',
'name': '[VM] VM1/VM1-flat.vmdk',
'key': 5,
'size': 32457621504
}
],
'capacity': 32505856,
'label': 'Hard disk 1',
'descriptor': '[VM] VM1/VM1.vmdk',
'committed': 31696896,
'device': {
'summary': '32,505,856 KB',
'_obj': <pysphere.vi_property.VIProperty object at 0x17442910>,
'unitNumber': 0,
'key': 2000,
'label': 'Hard disk 1',
'type': 'VirtualDisk',
'capacityInKB': 32505856
}
}
If I want to access, let's say the descriptor key value how would I go about this with Python? For some reason all of the combinations I've tried do not work.
Any help and guidance would be appreciated and if more information is needed I can provide. Thanks.
Lets call your main dictionary bob, because I like bob:
bob['files'] #get you the list with second dictionary
bob['files'][0] #get you the first item in the list, which is the nested 2nd dictionary
bob['files'][0]['type'] == 'diskDescriptor'

Categories