代码之家  ›  专栏  ›  技术社区  ›  S31

分析嵌套JSON字符串-类型不匹配错误

  •  0
  • S31  · 技术社区  · 6 年前

    我试图通过JSON字符串解析来提取一个项目,但遇到了一些问题。

    这是我解析的JSON字符串,我将它存储在一个名为 result :

    {"From":{"Chocolate":{"Price":1.0,"AsAtDate":"2018-05-04T00:00:00"},"Lime":{"Price":1.35415115,"AsAtDate":"2018-05-04T00:00:00"},"Strawberry":{"Price":1.19517151,"AsAtDate":"2018-05-04T00:00:00"},"Vanilla":{"Price":0.77522986,"AsAtDate":"2018-05-04T00:00:00"},"Blueberry":{"Price":1.00084071,"AsAtDate":"2018-05-04T00:00:00"},"Lemon":{"Price":0.75030012,"AsAtDate":"2018-05-04T00:00:00"}},"To":"Chocolate","RequestedDate":"2018-05-22T08:26:16"}
    

    我想提取的只是“价格”。我试着让它通过一个for循环-

    Dim result As String
    Dim Item As Variant
    Dim parsedResult As Object
    Dim i As Long
    Dim ws As Worksheet
    
    result = objHTTP.responseText
    
    Set ws = Worksheets("Sheet1")
    Set parsedResult = JsonConverter.ParseJson(result)
    
    i = 1
    
    For Each Item In parsedResult("From")
        ws.Cells(i, 2) = Item("Price")
        i = i + 1
    Next
    

    我不断地,不断地得到 type mismatch 错误

    ws.cells(i,2)=item(“价格”)

    这里有什么我定义错误的地方吗?我走了 结果 为了确保我得到了正确的要解析的JSON字符串(如上图所示),所以到这一点为止的一切都很好。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Sam    6 年前

    尝试用替换失败的行

    ws.Cells(i, 2) = parsedResult("From")(Item)("Price")
    
        2
  •  1
  •   Tehscript    6 年前

    我知道JSON解析器很容易实现这一点,但要演示如何从嵌套字典中获取结果,请参见以下内容:

    Set dict1 = parsedResult
    For Each Key1 In dict1
        Set dict2 = dict1("From")
        For Each Key2 In dict2
            Set dict3 = dict2(Key2)
            For Each Key3 In dict3
                Debug.Print dict3("Price")
            Next Key3
        Next Key2
    Next Key1