Code Editor
Learn
Gaining Insights

The flatten() Function

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 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.

Report a Bug
If you see a bug or any other issue with this page, please report it here.