Powershell ConvertTo-JSON返回“嵌套”对象

问题描述 投票:1回答:1

我正在尝试向我的服务器发出POST请求。一切都很好,直到我决定将我的对象转换为JSON。这是我的代码:

$postParams = @{
  Login = "JonSnow66";
  Password = "LetItSnow";
  Email = "[email protected]";

  Name = "Jon Snow";
  Desc = "I know nothing";
  BirthDate = "1572 2 16";
  Img = Get-Content -Path ./PH_img.txt | Out-String;
  Type = "Admin";
}

Invoke-WebRequest -Uri http://localhost:3000/api/add/user -Method POST -Body (ConvertTo-Json $postParams -Compress)

而不是返回常规的JSON对象,如:

{
"Login": "JonSnow66"
...
}

它返回:

{{
    "Login":  "JonSnow66",
    "BirthDate":  "1572 2 16",
    "Desc":  "I know nothing",
    "Name":  "Jon Snow",
    "Type":  "Admin",
    "Password":  "LetItSnow",
    "Img":  "/9j/4<BASE64>/Z\r\n",
    "Email":  "[email protected]"
}: ""}

我只是一个名副其实的初学者。

json node.js powershell
1个回答
1
投票

我认为你需要在Invoke-WebRequest上指定ContentType为'application / json'。如果您没有指定内容类型并且正在执行Post,那么我认为cmdlet假定您默认提交表单,这可能解释您在结果中看到的额外{ }字符。

这是修改后的代码:

Invoke-WebRequest -Uri 'http://localhost:3000/api/add/user' -Method POST  -ContentType 'application/json' -Body (ConvertTo-Json $postParams -Compress)
© www.soinside.com 2019 - 2024. All rights reserved.