在我的数组中解析 Azure Logic App 中的 JSON 时,我可以获得单个或多个值/对象(如下例所示的框)
两种类型的输入都是正确的,但是当只有一个对象出现时,它是 抛出错误“无效类型。预期数组但得到对象”
输入 1(抛出错误): -
{
"MyBoxCollection":
{
"Box":{
"BoxName": "Box 1"
}
}
}
输入 2(工作正常): -
{
"MyBoxCollection":
[
{
"Box":{
"BoxName": "Box 1"
},
"Box":{
"BoxName": "Box 2"
}
}]
}
JSON 模式:
"MyBoxCollection": {
"type": "object",
"properties": {
"box": {
"type": "array",
items": {
"type": "object",
"properties": {
"BoxName": {
"type": "string"
},
......
.....
..
}
错误详情:-
[
{
"message": "Invalid type. Expected Array but got Object .",
"lineNumber": 0,
"linePosition": 0,
"path": "Order.MyBoxCollection.Box",
"schemaId": "#/properties/Root/properties/MyBoxCollection/properties/Box",
"errorType": "type",
"childErrors": []
}
]
最佳答案
正如其他帖子所建议的那样,我曾经使用在结果集中注入(inject)几个虚拟行的技巧,但我最近找到了一种更好的方法。感谢 Thomas Prokov 在 his NETWORG blog post 中提供灵感.
JSON 解析模式接受多种选择作为类型,因此只需替换
"type": "array"
和"type": ["array","object"]
并且您的解析步骤将愉快地解析数组或单个值(或根本没有值)。然后,您可能需要确定您所处的场景:结果集中有 0、1 条或多条记录?我将在下面粘贴如何创建一个变量(ResultsetSize),该变量为您的开关采用 3 个值(rs_0、rs_1 或 rs_n)之一:
"Initialize_ResultsetSize": {
"inputs": {
"variables": [
{
"name": "ResultsetSize",
"type": "string",
"value": "rs_n"
}
]
},
"runAfter": {
"<replace_with_name_of_previous_action>": [
"Succeeded"
]
},
"type": "InitializeVariable"
},
"Check_if_resultset_is_0_or_1_records": {
"actions": {
"Set_ResultsetSize_to_0": {
"inputs": {
"name": "ResultsetSize",
"value": "rs_0"
},
"runAfter": {},
"type": "SetVariable"
}
},
"else": {
"actions": {
"Set_ResultsetSize_to_1": {
"inputs": {
"name": "ResultsetSize",
"value": "rs_1"
},
"runAfter": {},
"type": "SetVariable"
}
}
},
"expression": {
"and": [
{
"equals": [
"@string(body('<replace_with_name_of_Parse_JSON_action>')?['<replace_with_name_of_root_element>']?['<replace_with_name_of_list_container_element>']?['<replace_with_name_of_item_element>']?['<replace_with_non_null_element_or_attribute>'])",
""
]
}
]
},
"runAfter": {
"Initialize_ResultsetSize": [
"Succeeded"
]
},
"type": "If"
},
"Process_resultset_depending_on_ResultsetSize": {
"cases": {
"Case_no_record": {
"actions": {
},
"case": "rs_0"
},
"Case_one_record_only": {
"actions": {
},
"case": "rs_1"
}
},
"default": {
"actions": {
}
},
"expression": "@variables('ResultsetSize')",
"runAfter": {
"Check_if_resultset_is_0_or_1_records": [
"Succeeded",
"Failed",
"Skipped",
"TimedOut"
]
},
"type": "Switch"
}
关于json - 在逻辑应用程序 JSON 数组中解析单个对象的抛出错误但对于多个对象它工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58987668/