在excel VBA中使用VBA v2.0.1
下面是我从API查询获得的JSON响应
{
"currency": {
"code": "USD",
"name": "US Dollar",
"prefix": "$",
"postfix": null
},
"products": [
{
"product_id": xxxxx,
"model_code": "xxxxx",
"quantity": 1,
"price": "45.60",
"total": "45.60",
"retail_price": "63.84"
}
],
"shipping": [
{
"name": "UPS",
"price": 43.83,
"delivery": "3 -10 Days delivery"
},
{
"name": "DHL",
"price": 20.29,
"delivery": "2-6 days"
},
{
"name": "FedEx",
"price": 31.46,
"delivery": "2-6 days"
},
{
"name": "EMS",
"price": 25.74,
"delivery": "7 - 25 Days delivery"
},
{
"name": "Air Mail",
"price": 11.85,
"delivery": "10 - 25 Days delivery"
}
]
}
下面是我的代码的一部分,用于解析来自"Air“元素的价格。
result = objHTTP.responseText
Dim Json As Object
Dim resultAirmailprice As String
Set Json = JsonConverter.ParseJson(result)
resultAirmailprice = Json("shipping")(5)("price")
Cells(2, 2).Value = resultAirmailprice
当"Air“元素在”传送“元素的(5)中时,代码运行良好。问题是有时没有"UPS“和”空邮“元素,所以我得到了一个错误。
如何编写代码解析“空邮”价格,如果不存在,解析从"EMS“价格(或最便宜的价格)?
发布于 2016-04-23 15:32:19
查看Json解析器代码,它返回一个Dictionary对象,该对象包含其他Dictionary对象(子键),对于数组,它返回Collection对象。在Json中,我看到“传送”是一个数组,因此解析器返回一个Collection对象。
因此,您可以使用所有的集合成员和方法来操作和访问它。特别是,您可以使用Json("shipping").Count
来检查船运集合有多少个元素。或者可以使用For each x in Json("shipping")
迭代集合。
要检查您是否有字典或集合,可以使用TypeName
函数或TypeOf..Is
运算符。
https://stackoverflow.com/questions/36812365
复制相似问题