Learn

The analyze() function we just created will return the results from the Personality Insight (PI) API in JSON format. Whenever we use the analyze() function, we’ll need to parse and flatten the JSON results to make use of them later.

By default, PI creates a tree structure for various categories. These categories are broken into Personality, Values, and Needs. These are then are broken into subcategories, and finally, broken into the actual traits.

For this application, we’ll compare the traits by flattening the structure and then extracting only the traits.

The flatten() function below will flatten the JSON structure that the analyze() function returns from PI.

def flatten(orig): data = {} for c in orig['tree']['children']: if 'children' in c: for c2 in c['children']: if 'children' in c2: for c3 in c2['children']: if 'children' in c3: for c4 in c3['children']: if (c4['category'] == 'personality'): data[c4['id']] = c4['percentage'] if 'children' not in c3: if (c3['category'] == 'personality'): data[c3['id']] = c3['percentage'] return data

It’s not important to understand exactly how the flatten() function works. What’s important is to make sure we include it as part of our application so that we can properly process PI results.

Instructions

1.

Add the flatten() function to your application. It should take one argument called orig. Place it after the analyze() function.

Click Run to save your code.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?