Shabar
Shabar

Reputation: 2811

Parsing json with Powershell in cURL

Hi I am trying to execute below ways to run the POST call in power shell

option 1:

$Body="{ \`"cartItem\`" : {\`"sku\`" : \`"RG1219013\`", \`"qty\`" : \`"1\`",  \`"quoteId\`" : \`"QRAeZdoFbieEWHjrRs5X0G1tHRE4el30\`"  }}"

option 2:

$Body=@"
{ \"cartItem\" : {\"sku\" : \"RG1219013\", \"qty\" : \"1\",  \"quoteId\" : \"QRAeZdoFbieEWHjrRs5X0G1tHRE4el30\"  }}
"@

option3 :

$Body = @{
    cartItem =
    {
        sku = 'RG1219013'
        qty = '1'
        quoteId = 'QRAeZdoFbieEWHjrRs5X0G1tHRE4el30'
    }
} 

$Json = (ConvertTo-Json $Body)

Execute:

$Header = @{ "Content-Type" = "application/json" }
Invoke-RestMethod -Method Post -Body $Body -Uri $UriAddtoCart -Header $Header

In option 1 and option 2 I am getting Bad request (400) and option 3 it's internal error (500)

Below jason respond successfully through postman

{
    "cartItem" :
    {
        "sku" : "RG1219013",
        "qty" : "1",
        "quoteId" : "QRAeZdoFbieEWHjrRs5X0G1tHRE4el30"
    }
}

Is there anything missing here?

Upvotes: 0

Views: 425

Answers (1)

iRon
iRon

Reputation: 23623

The Json file is missing a @ sign after cartItem = in option 3 (this way a function is assigned to the cartItem property rather than a HashTable)
This will get clear if you output the $Json file (e.g. Write-Host $Json).

Thus:

$Body = @{
    cartItem =
    {
        sku = 'RG1219013'
        ...

Should be:

$Body = @{
    cartItem =
    @{
        sku = 'RG1219013'
        ...

Upvotes: 1

Related Questions