2

I am new to python and django.

For my application in my django view, I am accepting array (and sub arrays) of JSON objects as request, by using json.loads I am trying to parse and iterate thru JSON objects but facing issues while parsing.

my javascript object sent from client is

var JSONObject = { 
       "employees_companyA": 
        [
          { "firstName":"John" , "lastName":"Doe" }, 
          { "firstName":"Anna" , "lastName":"Smith" }, 
          { "firstName":"Peter" , "lastName":"Jones" }
        ],

      "employees_companyB": 
        [
          { "firstName":"John" , "lastName":"Doe" }, 
          { "firstName":"Anna" , "lastName":"Smith" }, 
          { "firstName":"Peter" , "lastName":"Jones" }
        ]
     };

What is the best way to parse above two objects and read firstName, lastName for same.

I tried using o["firstName"], o.firstName etc (below is my code snippet)

   json_obj = json.loads(request.POST['json_test']) 
   for o in json_obj:
        temp_arr.append(o["firstName"])

I am sure this would be pretty straightforward but I couldn't find exact help here.

0

1 Answer 1

2

The top-level element of your JSON structure is not a list, but a mapping. It's keys are of the form "employees_companyA", "employees_companyB", etc.

You need to thus address that structure using the python mapping interface instead:

for value in json_obj.itervalues():
     temp_arr.append(value[0]["firstName"])

or as a one-liner:

temp_arr = [value[0]['firstName'] for value in json_obj.itervalues()]

Both use the .itervalues() method on json_obj to loop over all the values in the structure.

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

1 Comment

Thanks, it worked, I did following on top of what you suggested for o in json_obj.itervalues(): temp_arr.append(o[0]['firstName'])

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.