从json对象中提取数据

时间:2012-10-15 09:55:56

标签: json excel vba

我有Json的样子 {“valid”:“true”,“isinCode”:null,“lastUpdateTime”:“15-OCT-2012 14:18:56”,“tradedDate”:“15OCT2012”,“data”:[{“change”: “16.75”, “lastPrice”: “5,703.30”}

我已经能够使用jsonlib将其解压缩为JSON对象。

如何从中提取'lastPrice'作为嵌套的json(数据是另一个json对象)?

1 个答案:

答案 0 :(得分:1)

我使用类似下面的内容,虽然它非常特定于JSON,但是每次我需要解析新数据时都要重新点亮:

Public Sub ReadJson()

    Const JsonString    As String = "{""valid"":""true"",""isinCode"":null,""lastUpdateTime"":""15-OCT-2012 14:18:56"",""tradedDate"":""15OCT2012"",""data"":[{""change"":""16.75"",""lastPrice"":""5,703.30""}]}"
    Dim objJson         As Object
    Dim objSE           As Object

    Set objSE = CreateObject("ScriptControl")

    With objSE
        .Language = "JScript"
        .AddCode "function getProp(jsonObj, propertyName) { return jsonObj[propertyName]; } "
        .AddCode "function getSubProp(jsonObj, pName, propertyName) { return jsonObj[pName][0][propertyName]; } "
    End With

    With objSE
        Set objJson = .Eval("(" + JsonString + ")")
        Debug.Print .Run("getProp", objJson, "valid")
        Debug.Print .Run("getProp", objJson, "isinCode")
        Debug.Print .Run("getProp", objJson, "lastUpdateTime")
        Debug.Print .Run("getProp", objJson, "tradedDate")
        Debug.Print .Run("getSubProp", objJson, "data", "change")
        Debug.Print .Run("getSubProp", objJson, "data", "lastPrice")
    End With

End Sub