我有一堆 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-RestMethod和 Write-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
关于json - 调用 REST api 并将生成的 json 数据插入 SQL Server 的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72269715/