【问题标题】:Python API Output into 1st Normalized FormPython API 输出到第一规范化形式
【发布时间】:2021-12-24 13:17:14
【问题描述】:

我的数据看起来像这样,来自 API:

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

如何使用 Python 输出数据,使其看起来像这样:

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

【问题讨论】:

  • json 无效。可以更新吗?

标签: python python-3.x pandas api


【解决方案1】:

使用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

【讨论】:

  • 为什么在第一行 ['Customers'] 之前的“j”?那有什么作用?
  • @ChickenSandwichNoPickles - 答案已编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-21
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
  • 2022-07-12
  • 2020-08-03
  • 2014-09-20
相关资源
最近更新 更多