【问题标题】:Converting from json to dataframe to sql从 json 到 dataframe 到 sql 的转换
【发布时间】: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


    【解决方案1】:

    我认为 tagIDs 字段是一个列表,您的数据库似乎对此并不满意。

    不确定这是最好的方法,但您可以尝试将其从列表转换为字符串

    df['tagIDs'] = df['tagIDs'].apply(lambda x: str(x))
    

    【讨论】:

    • 是的,这就是我想要做的。谢谢!只是想知道你知道为什么 sql 数据库不接受列表作为变量吗?
    猜你喜欢
    • 2018-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-19
    相关资源
    最近更新 更多