【发布时间】:2020-12-10 18:23:08
【问题描述】:
我正在尝试将所有 json 数据保存到 sql 数据库中,并且我正在使用 python,所以我决定使用 pandas。
JSON 的一部分:
{
"stores": [
{
"ID": "123456",
"name": "Store 1",
"status": "Active",
"date": "2019-03-28T15:20:00Z",
"tagIDs": null,
"location": {
"cityID": 2,
"countryID": 4,
"geoLocation": {
"latitude": 1.13121,
"longitude": 103.4324231
},
"postcode": "123456",
"address": ""
},
"new": false
},
{
"ID": "223456",
"name": "Store 2",
"status": "Active",
"date": "2020-03-28T15:20:00Z",
"tagIDs": [
12,
35
],
"location": {
"cityID": 21,
"countryID": 5,
"geoLocation": {
"latitude": 1.12512,
"longitude": 103.23342
},
"postcode": "223456",
"address": ""
},
"new": true
}
]
}
我的代码:
response = requests.get(.....)
result = response.text
data = json.loads(result)
df = pd.json_normalize(data["store"])
.....
db_connection = sqlalchemy.create_engine(.....)
df.to_sql(con=db_connection, name="store", if_exists="append" )
Error: _mysql_connector.MySQLInterfaceError: Python type list cannot be converted
我希望数据框的实际外观如何:
ID tagIDs date
0 123456 [] 2020-04-23T09:32:26Z
1 223456 [12,35] 2019-05-24T03:21:39Z
2 323456 [709,1493] 2019-03-28T15:38:39Z
到目前为止,我尝试使用不同的数据框和 json 对象,它们都可以工作。
所以我发现问题出在 json 对象上。
没有“tagID”,其他一切都可以正常工作。
我在想,如果我将对象转换为字符串,它可以解析为 sql,但它也不起作用。如何更改 tagID 以便我可以将所有内容解析为 sql?或者还有其他更有效的方法吗?
【问题讨论】:
标签: python sql json pandas dataframe