Reputation: 163
I'm trying to take a json response and create as many objects that are contained in the response. Based on the text below, I want variable to be based on "testuser1" and the next variable to be based on "testuser2", and so on. Im able to convert the response to a dictionary but I'm sure how to count the objects and make variables out of each so I can refer and change them later in the code.
{'Accounts':
[
{'Name': 'testuser1',
'Username': 'testuser1',
'Email': '[email protected]'},
{'Name': 'testuser2',
'Username': 'testuser2',
'Email': '[email protected]'}
]
Basically, I want to count and create as many objects that are in the response. I don't want to use the split function to look for the {}. For example: $var1 = {'Name': 'testuser1', 'Username': 'testuser2=1', 'Email': '[email protected]'} and $var2 = {'Name': 'testuser2', 'Username': 'testuser2', 'Email': '[email protected]'}
Upvotes: 1
Views: 44
Reputation: 163
Now that I think about this problem, I believe I'm approaching it wrong. I shouldn't be trying to convert this data because I can refer to each element of the dictionary. Converting to a variable is redundant.
Thanks for everyones help with a noob python approach and problem.
Upvotes: 1
Reputation: 3036
This works for python 3:
import json
response = ... # Your json response
d = json.loads(response)
obj_list = []
total_obj = len(d['Accounts'])
for index in range(tot_obj):
obj_list.append(d['Accounts'][index])
var1 = obj_list[0] # Optionally, var1 = d['Accounts'][0]
var2 = obj_list[1]
The method json.loads()
converts a string
to dictionary
while json.dumps()
does that the other way round.
Check out this documentation to know more: json module
You can store the variables in a list which could be accessed using indices.
Upvotes: 0