Invoke-WebRequest \ RestMethod mangle json string with escapes

时间:2017-04-12 13:29:43

标签: json powershell azure

我的字符串:

{"properties":{"template":{"contentVersion":"1.0.0.0","$schema":"https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#","resources":"{"type":"Microsoft.Network/networkSecurityGroups","name":"[parameters('GroupName')]","apiVersion":"2016-03-30","location":"[resourceGroup().Location]","properties":{"securityRules":["@{name=DenyAll; properties=}"]}}","parameters":"{"GroupName":{"defaultValue":"GroupName","type":"String"}}"},"mode":"Incremental"}}

在执行invoke-webrequest \ restmethod:

时,Powershell会像这样破坏它
\"{\"properties\":{\"template\":{\"contentVersion\":\"1.0.0.0\",\"$schema\":\"https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#\",\"resources\":\"{\"type\":\"Microsoft.Network/networkSecurityGroups\",\"name\":\"[parameters('GroupName')]\",\"apiVersion\":\"2016-03-30\",\"location\":\"[resourceGroup().Location]\",\"properties\":{\"securityRules\":[\"@{name=DenyAll; properties=}\"]}}\",\"parameters\":\"{\"GroupName\":{\"defaultValue\":\"GroupName\",\"type\":\"String\"}}\"},\"mode\":\"Incremental\"}}\"

这让Azure真的很不高兴。如何避免?

我的电话:

iwr $url -Headers $headers -Body $body -Method Put -ContentType 'application/json'

基本上我必须这样做:

$(get-content path -Raw -ReadCount 0) | ConvertFrom-Json

然后用它来传递它

1 个答案:

答案 0 :(得分:1)

首先检查两个东西,JSON对象的主体并验证字符串是否符合JSON结构会很好。

我在初始字符串中发现了错误,在JSON中有效的格式是:

{"properties":{"template": {"contentVersion": "1.0.0.0","$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#","resources": {"type": "Microsoft.Network/networkSecurityGroups","name": "[parameters('GroupName')]","apiVersion":"2016-03-30","location":"[resourceGroup().Location]","properties": {"securityRules": ["@{name=DenyAll; properties=}"]}},"parameters":{"GroupName":{"defaultValue":"GroupName","type": "String"}}},"mode":"Incremental"}}

此转换可在http://jsonlint.com/完成 现在,您可以使用任何常用编辑器(如notepad ++)转义字符串并加入一个简单的行,最后转义为url中的字符串

 {\"properties\": {\"template\": {\"contentVersion\": \"1.0.0.0\",\"$schema\": \"https:\/\/schema.management.azure.com\/schemas\/2015-01-01\/deploymentTemplate.json#\",\"resources\": {\"type\": \"Microsoft.Network\/networkSecurityGroups\",\"name\": \"[parameters('GroupName')]\",\"apiVersion\": \"2016-03-30\",\"location\": \"[resourceGroup().Location]\",\"properties\": {\"securityRules\": [\"@{name=DenyAll; properties=}\"]}},\"parameters \": {\"GroupName\": {\"defaultValue\": \"GroupName\",\"type\": \"String\"}}},\"mode \": \"Incremental\"}}

如果你需要测试一些服务使用PostMan

,那么另一个建议

然后再次尝试通话。 问候。