【问题标题】:Unable to ingest JSON data into Azure Event Hub无法将 JSON 数据引入 Azure 事件中心
【发布时间】:2020-11-10 16:35:32
【问题描述】:

我编写了以下 Powershell 脚本以从 API 端点 (https://data.melbourne.vic.gov.au/resource/vh2v-4nfs) 获取 JSON 数据,然后以 JSON 格式将此数据写入 Azure 事件中心。我能够成功地从端点获取数据,但是数据没有被摄取到 Azure 事件中心。

谁能告诉我以下代码有什么问题:

$url = "https://data.melbourne.vic.gov.au/resource/vh2v-4nfs"
$apptoken = "k7lQcUCVFoROv7rQh9fSSXMkZ"

# Set header to accept JSON
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept","application/json")
$headers.Add("X-App-Token",$apptoken)

$results = Invoke-RestMethod -Uri $url -Method get -Headers $headers

$results


$method = "POST"
$URI = "https://YOURNS.servicebus.windows.net/eh-streetparking/messages"
$signature = "SharedAccessSignature sr=YOURNS.servicebus.windows.net%2feh-streetparking&sig=K6bfL1VjW9FUcL0B5xaI%3d&se=16722&skn=eh-sap-streetparking"

#$authInfo = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$signature"))

# API headers
$headers = @{
            "Authorization"=$signature;
#            "Content-Type"="application/json;type=entry;charset=utf-8";
            "Content-Type"="application/json";
            }


# execute the Azure REST API

foreach ( $result in $results)
{
Invoke-RestMethod -Uri $URI -Method $method -Headers $headers -Body $result
}

【问题讨论】:

  • 错误是什么?

标签: powershell azure-eventhub


【解决方案1】:

您作为Invoke-RestMethod 的返回结果提供的值实际上是一个反序列化的 PowerShell 对象,而不是 JSON。它似乎也在某个时候删除了它的引号。

PSObject ($results) 看起来像这样:$x = @{account_id="12345"; username="12345"; is_locked="False"; employee_id="12345"; first_name="John"; middle_initial="Roger"; last_name="Doe"; full_name="John Roger Doe"}

您可以这样做来访问单个值:

$x.full_name

最后关注this syntax发送POST请求:

$Cred = Get-Credential
$Url = "https://server.contoso.com:8089/services/search/jobs/export"
$Body = @{
    search = "search index=_internal | reverse | table index,host,source,sourcetype,_raw"
    output_mode = "csv"
    earliest_time = "-2d@d"
    latest_time = "-1d@d"
}
Invoke-RestMethod -Method 'Post' -Uri $url -Credential $Cred -Body $body -OutFile output.csv

【讨论】:

  • 如何将其序列化回 JSON?此外,是否有更好的脚本来实现这一点,如果它有助于仅以 JSON 格式摄取文件,我愿意使用任何其他脚本,如 C# 或任何其他语言。请与我分享任何指针或相关示例。
  • 我使用 ConvertTo-Json 实用程序通过了对 JSON 的转换,现在它因“Invoke-RestMethod:远程服务器返回错误:(413) 请求实体太大而失败。”
  • 已针对此错误提出另一个问题stackoverflow.com/questions/64778754/…
猜你喜欢
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-24
  • 2016-12-26
相关资源
最近更新 更多