有什么办法可以将下面的嵌套json数据插入到SQL Server中

时间:2019-04-09 13:41:05

标签: sql json sql-server ssis ssis-2012

我正在处理需要加载到SQL SERVER 2012中的嵌套JSON数据。嵌套的JSON包含两个根,即一列和另一行。我需要将行中的值放入列中。请参见以下结构:

{
    "tables": [
        {
            "name": "PrimaryResult",
            "columns": [
                {
                    "name": "timestamp",
                    "type": "datetime"
                },
                {
                    "name": "id",
                    "type": "string"
                },
                {
                    "name": "name",
                    "type": "string"
                },
                {
                    "name": "url",
                    "type": "string"
                },
                {
                    "name": "duration",
                    "type": "real"
                }
            ],
            "rows": [
                [
                    "2019-04-08T13:09:52.871Z",
                    "244",
                    "Internal",
                    "https://google.com",
                    1245,

                ]
            ]
        }
    ]
}

结果:

timestamp    id    name    url    duration
2019-04-08    244    Internal    https://google.com    1245

这里,在sql server中,它应该从列中获取列名,并从行中获取每一列的值

1 个答案:

答案 0 :(得分:2)

假设您将json存储到名为json.txt的文件中

import json

with open('json.txt') as f:
    data = json.load(f)
    tableName = data['tables'][0]["name"]
    sqlCreateTable = 'CREATE TABLE ' + tableName + ' (\n'
    sqlInsertInto = 'INSERT INTO ' + tableName + ' ('
    for i in range(0,len(data['tables'][0]['columns'])):
        columnName = data['tables'][0]['columns'][i]['name']
        type = data['tables'][0]['columns'][i]['type']
        sqlCreateTable += columnName + " " + type + ',\n'
        sqlInsertInto += columnName + ', '

    sqlCreateTable = sqlCreateTable[:-2] + '\n);'
    sqlInsertInto = sqlInsertInto[:-2] + ')\nVALUES ('

    for value in data['tables'][0]['rows'][0]:
        sqlInsertInto += str(value) + ', '

    sqlInsertInto = sqlInsertInto[:-2] + ');'

    print(sqlCreateTable)
    print(sqlInsertInto)

创建表的输出:

CREATE TABLE PrimaryResult (
timestamp datetime,
id string,
name string,
url string,
duration real
);

插入表的输出:

INSERT INTO PrimaryResult (timestamp, id, name, url, duration)
VALUES (2019-04-08T13:09:52.871Z, 244, Internal, https://google.com, 1245);