1

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]'}

1
  • Just leave them in the dictionary. Commented Jun 26, 2018 at 2:04

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Yes, but how can I create variables of each subdirectory of "Accounts"? Based on example above it should create 2 variables. For example: $var1 = {'Name': 'testuser1', 'Username': 'testuser2=1', 'Email': '[email protected]'} and $var2 = {'Name': 'testuser2', 'Username': 'testuser2', 'Email': '[email protected]'}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.