json - 调用 REST api 并将生成的 json 数据插入 SQL Server 的最简单方法

标签 json sql-server powershell rest

我有一堆 REST API 调用,它们返回扁平的 json 数据,我想定期调用这些数据并将其转储到 SQL Server 数据库中。无需编写大量代码即可完成此操作的简单方法是什么?我在 Windows 平台上,很高兴使用 C#、Powershell、T-SQL、SSIS 或 Windows 平台上的其他“常规”工具。

我不想根据 json 字段手动编写任何内容,也就是说,如果它可以自动查看 json 并在 SQL Server 中创建目标表,或者至少主要为以下内容进行映射,那就太好了我。

一般来说,我的 API 结果是一组外观相似的 json 对象,没有嵌套对象。不同的 API 调用具有不同字段的 json 对象,但任何一次调用的结果都具有相同的字段,例如

[ 
    {
      "id": "abc",
      "quantity": 1234,
      "price": 3456.03,
      "entityId": 99,
      "anotherField": "cows"
    },
...
]

最佳答案

我最喜欢的解决方案是使用 Powershell Invoke-RestMethodWrite-SqlTableData ,因为它避免提前创建 SQL 表或编写任何特定于字段或列的内容。还可以使用 Invoke-Sqlcmd如果你想做其他 SQL 事情,例如在每次导入之前清除暂存表。

$url = 'https://jsonplaceholder.typicode.com/todos'

# Add any headers needed, e.g. Authorization headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type", "application/json")

# call the REST api and get results as an array of objects
$response = Invoke-RestMethod $url-Method 'GET' -Headers $headers    

# clear out the table ahead of each load. Use 'drop table' instead if the schema might change.
Invoke-Sqlcmd -Query "if object_id('dbo.import_todos', 'U') is not null begin truncate table dbo.import_todos; end" -ServerInstance . -Database 'scratch'

# Dump the api results into a DB table. This will create the table if it doesn't already exist.
# To use this cmdlet first install it using: Install-Module SQLServer
Write-SqlTableData -ServerInstance '.' -DatabaseName 'scratch' -SchemaName "dbo" `
                   -TableName "import_todos" -InputData $response -Force

文章herehere非常有帮助。

关于json - 调用 REST api 并将生成的 json 数据插入 SQL Server 的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72269715/

相关文章:

mysql - 如果mysql json字段不存在则追加

json - 在 Swift 中将可选元素附加到 json 数组中

sql - 摆脱 SQL Server 中的 "Magic"数字

sql-server - 什么类型的错误导致 XACT_STATE 在 MS SQL Server 中为 1?

powershell - 在 PowerShell 中将参数传递给 $webclient.DownloadFile()

sorting - powershell 排序多维数组

java - jackson :反序列化到一个集合

sql - 在一个 select 语句中使用一个 where 子句可以有多个链接服务器吗?

powershell - 如果设置了数据类型,参数值不能设置为空

json - 使用请求模块检索 JSON 并返回值