循环数组中的json以在vba中获得相同的值

时间:2019-07-04 09:49:09

标签: json vba web-scraping

我正在尝试从下面的json中获取行的不同列中的“ image_id”。

[
{
"spin": "HM4C6L",
"attributes": {
"product name": "Everest Kutilal Coarse Ground Red Chilli Powder ",
},
"bar_code": {
"valid": true,
"id": "89017817",
"type": "UPC"
},
"spin_state": "LIVE",
"meta": {
"updated-by": "undefined"
},
"version": null,
"images": [
{
"image_id": "dvuewrnauxdroqcapjiu",
"image_name": "masala and spice_HM4A7I2C6L_MN.JPG",
"shot_type": "MN"
},
{
"image_id": "tcku7lwarkv8ch0ao9cu",
"image_name": "masala and spice_HM4A7I2C6L_AL1.JPG",
"shot_type": "AL1"
},
{
"image_id": "b2znlmm59plprrkmkujs",
"image_name": "masala and spice_HM4A7I2C6L_AL2.jpg",
"shot_type": "AL2"
}
]
}
]

I tried solutions given: Cannot iterate when parsing HTML table using JSON-VBA and Loop through the JSON object keys in excel vba but none works for me.

[
{
"spin": "HM4C6L",
"attributes": {
"product name": "Everest Kutilal Coarse Ground Red Chilli Powder ",
},
"bar_code": {
"valid": true,
"id": "89017817",
"type": "UPC"
},
"spin_state": "LIVE",
"meta": {
"updated-by": "undefined"
},
"version": null,
"images": [
{
"image_id": "dvuewrnauxdroqcapjiu",
"image_name": "masala and spice_HM4A7I2C6L_MN.JPG",
"shot_type": "MN"
},
{
"image_id": "tcku7lwarkv8ch0ao9cu",
"image_name": "masala and spice_HM4A7I2C6L_AL1.JPG",
"shot_type": "AL1"
},
{
"image_id": "b2znlmm59plprrkmkujs",
"image_name": "masala and spice_HM4A7I2C6L_AL2.jpg",
"shot_type": "AL2"
}
]
}
]

在单元格B2中需要“ dvuewrnauxdroqcapjiu”,在单元格C2中需要tcku7lwarkv8ch0ao9cu,在单元格C2中需要“ b2znlmm59plprrkmkujs”,但是我的代码没有输出,也没有错误。

请帮助。

1 个答案:

答案 0 :(得分:3)

很多东西。

  1. 您的json格式不正确。这里有一个额外的“,”:

"Everest Kutilal Coarse Ground Red Chilli Powder ",

这意味着jsonconverter将引发错误。最后的“,”是将当前键值对与下一个分开。没有下一对,因此应将其删除。

  1. 您的访问路径错误。

这里我正在从单元格A1中读取更正的json

Option Explicit   
Public Sub test()
    Dim json As Object, i As Long, item As Object, c As Long
    i = 2: c = 2
    Set json = JsonConverter.ParseJson([A1])(1)("images")
    For Each item In json
        ActiveSheet.Cells(i, c) = item("image_id")
        c = c + 1
    Next
End Sub
  1. Cells(2,B)期望B是一个变量,因为字符串文字被包装在“”即“ B”中。另外,您需要一个递增的计数器变量,否则将继续写入同一单元格。