【问题标题】:Python variable appears to be json but with quotes throughoutPython 变量似乎是 json,但始终带有引号
【发布时间】:2020-05-20 05:56:33
【问题描述】:

我是 Python 新手;在这里使用 Jupyter nb。

将变量设置为az cli 命令的结果时,我得到一个json 数组,但其中包含单引号。

当我单独运行命令而不将其设置为变量时,响应是干净的 json。

如何将变量结果作为干净的 json?

示例 1:(已通过使用 .join 修复,如 cmets 中所述)

new_mi = !az identity create --name $mi_name --resource-group $rg_name --location $rc_location
new_mi
['{',
 '  "clientId": "redacto",',
 '  "clientSecretUrl": "https://control-westus2.identity.azure.net/subscriptions/redacto/resourcegroups/rg_azureFunction/providers/Microsoft.ManagedIdentity/userAssignedIdentities/mi_azureFunction/credentials?tid=redacto&oid=redacto&aid=redacto",',
 '  "id": "/subscriptions/redacto/resourcegroups/rg_azureFunction/providers/Microsoft.ManagedIdentity/userAssignedIdentities/mi_azureFunction",',
 '  "location": "westus2",',
 '  "name": "mi_azureFunction",',
 '  "principalId": "redacto",',
 '  "resourceGroup": "rg_azureFunction",',
 '  "tags": {',
 '    "lang": "python",',
 '    "owner": "redacto",',
 '    "project": "test"',
 '  },',
 '  "tenantId": "redacto",',
 '  "type": "Microsoft.ManagedIdentity/userAssignedIdentities"',
 '}']

示例2:不同的az cli 命令,但.join 在这里不起作用

  • 我不认为响应,即使.join 是有效的 json,因为开头的消息。
  • 如何跳过此步骤并直接转到 .join 的 json 对象?
sa_new = !az storage account create --name $sa_name --resource-group $rg_name --access-tier Cool --default-action Deny --kind StorageV2 --sku Standard_LRS --subscription $sub_id --tags $sa_tags

sa_new

["WARNING: The default kind for created storage account will change to 'StorageV2' from 'Storage' in the future",
 '{',
 '  "accessTier": "Cool",',
 '  "azureFilesIdentityBasedAuthentication": null,',
 '  "creationTime": "2020-05-21T05:28:13.115847+00:00",',
 '  "customDomain": null,',
 '  "enableHttpsTrafficOnly": true,',
 '  "encryption": {',
 '    "keySource": "Microsoft.Storage",',
 '    "keyVaultProperties": null,',
 '    "services": {',
 '      "blob": {',
 '        "enabled": true,',
 '        "lastEnabledTime": "2020-05-21T05:28:13.193965+00:00"',
 '      },',
 '      "file": {',
 '        "enabled": true,',
 '        "lastEnabledTime": "2020-05-21T05:28:13.193965+00:00"',
 '      },',
 '      "queue": null,',
 '      "table": null',
 '    }',
 '  },',
 '  "failoverInProgress": null,',
 '  "geoReplicationStats": null,',
 '  "id": "/subscriptions/redacto/resourceGroups/redacto/providers/Microsoft.Storage/storageAccounts/redacto",',
 '  "identity": null,',
 '  "isHnsEnabled": null,',
 '  "kind": "StorageV2",',
 '  "largeFileSharesState": null,',
 '  "lastGeoFailoverTime": null,',
 '  "location": "westus2",',
 '  "name": "redacto",',
 '  "networkRuleSet": {',
 '    "bypass": "AzureServices",',
 '    "defaultAction": "Deny",',
 '    "ipRules": [],',
 '    "virtualNetworkRules": []',
 '  },',
 '  "primaryEndpoints": {',
 '    "blob": "https://redacto.blob.core.windows.net/",',
 '    "dfs": "https://redacto.dfs.core.windows.net/",',
 '    "file": "https://redacto.file.core.windows.net/",',
 '    "queue": "https://redacto.queue.core.windows.net/",',
 '    "table": "https://redacto.table.core.windows.net/",',
 '    "web": "https://redacto.z5.web.core.windows.net/"',
 '  },',
 '  "primaryLocation": "westus2",',
 '  "provisioningState": "Succeeded",',
 '  "resourceGroup": "redacto",',
 '  "secondaryEndpoints": null,',
 '  "secondaryLocation": null,',
 '  "sku": {',
 '    "capabilities": null,',
 '    "kind": null,',
 '    "locations": null,',
 '    "name": "Standard_LRS",',
 '    "resourceType": null,',
 '    "restrictions": null,',
 '    "tier": "Standard"',
 '  },',
 '  "statusOfPrimary": "available",',
 '  "statusOfSecondary": null,',
 '  "tags": {',
 '    "owner": "redacto",',
 '    "project": "test"',
 '  },',
 '  "type": "Microsoft.Storage/storageAccounts"',
 '}']

sa_new = json.loads("\n".join(sa_new))

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Example3:此命令有同样的问题,顶部的“WARNING”消息使响应无效 JSON

az_new = !az functionapp create --consumption-plan-location westus --name $af_name --os-type Linux --resource-group $rg_name --runtime python --storage-account $sa_name --disable-app-insights true

az_new

["WARNING: Your Linux function app 'redacto', that uses a consumption plan has been successfullycreated but is not active until content is published usingAzure Portal or the Functions Core Tools.",
 '{',
 '  "availabilityState": "Normal",',
 '  "clientAffinityEnabled": false,',...

【问题讨论】:

  • 因为它将每一行作为单独的字符串提供给您,只需加入它们
  • 另外,在有了一个干净的字符串之后,如果你想把它作为一个json对象,你可以只导入json然后json.loads(docs.python.org/3/library/json.html
  • 我试过json.loads(new_mi)。结果TypeError: the JSON object must be str, bytes or bytearray, not 'SList'
  • 如果你想直接处理结果,你必须把它加入一个字符串,如json.loads("\n".join(new_mi))
  • @tmrlvi,这行得通。谢谢你。 new_mi = json.loads("\n".join(new_mi))。然后我可以使用new_mi['clientId'] 等访问json 对象的元素。如果你想更新你的答案,我可以接受。 (无法获得subprocess 的答案)

标签: python jupyter azure-cli


【解决方案1】:

当您在 Jupyter 中使用 ! 运行命令时,它会将输出作为行列表返回。更方便的方法可能是使用os.popensubprocess.run 或类似命令,然后解析json。

import os
import json

json.loads(os.popen("az identity create --name $mi_name --resource-group $rg_name --location $rc_location
new_mi").read())

【讨论】:

  • 感谢您在这里付出的额外努力,但我也无法让os.popen 工作。
猜你喜欢
  • 2014-06-30
  • 1970-01-01
  • 2016-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多