Home > Blockchain >  Python API Output into 1st Normalized Form
Python API Output into 1st Normalized Form

Time:11-13

I have data that looks like this, coming out of an API:

    {
      "Customers": [
        {
          "first_name": "John",
          "last_name": "Doe",
          "middle_initial": null,
          "phone_numbers": [
            {
              "id": "1",
              "primary": false,
            },
            {
              "id": "2",
              "primary": true,
     
            }
    
          ]
}

How can I output the data so that it looks like this, using Python:

first_name     last_name     middle_initial     phone_number_id     phone_number_primary
john           doe           null               1                   false
john           doe           null               2                   true

CodePudding user response:

Use json_normalize:

import json, requests

#from file
with open('myJson.json') as data_file:    
    d = json.load(data_file) 

#from API
d = requests.get(url).json()

df = pd.json_normalize(d['Customers'], 
                      'phone_numbers', 
                       ['first_name','last_name','middle_initial'],
                       record_prefix='phone_numbers_')
print (df)

  phone_numbers_id  phone_numbers_primary first_name last_name middle_initial
0                1                  False       John       Doe           None
1                2                   True       John       Doe           None
  • Related