无法将JSON数据导入Azure Event Hub

问题描述

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

任何人都可以让我知道以下代码有什么问题吗?

$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
}

解决方法

您作为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