规范嵌套JSON

owfi6suc  于 2023-07-01  发布在  其他
关注(0)|答案(1)|浏览(110)

我需要将JSON标准化。下面是我的代码片段

import pandas as pd 
data = [{
   "ActionID":"I",
   "Date":"01/13/2020",
   "SecInfo":[
      {
         "SecID":96964,
         "IssuerID":35,
         "StoreInfo":[
            {
               "Code":"3342",
               "Symbol":"LPPER",
               "Status":"A"
            }
         ]
      }
   ]
}]
col_name = []
for x in data[0]:
    col_name.append(x)
# for j in data[0]['SecInfo'][0]:
#     col_name. append(j)
df = pd.json_normalize(data, record_path=['SecInfo', ['StoreInfo']], meta=col_name, errors='ignore')
df.to_csv('gg.csv')

输出csv:

Code,Symbol,Status,ActionID,Date,SecInfo
3342,LPPER,A,I,01/13/2020,"{'SecID': 96964, 'IssuerID': 35, 'StoreInfo': [{'Code': '3342', 'Symbol': 'LPPER', 'Status': 'A'}]}"

正如你所看到的,"SecID""IssuerID"丢失了,我怎么才能把它们也正常化呢?
所需输出:

Code Symbol Status ActionID       Date       SecID   IssuerID
3342  LPPER  A     I        01/13/2020       96964         35

谢谢

enyaitl3

enyaitl31#

你需要在你进入的时候将关卡嵌套到 meta中:

df = pd.json_normalize(
    data=data,
    meta=["ActionID", "Date", ["SecInfo", "SecID"], ["SecInfo", "IssuerID"]],
    record_path=["SecInfo", "StoreInfo"]
)
df.columns = df.columns.str.split(".").str[-1]
print(df)

输出:

Code Symbol Status ActionID        Date  SecID IssuerID
0  3342  LPPER      A        I  01/13/2020  96964       35

相关问题