Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I have a json like below:

{"sentences":[{"trans":"something ru","orig":"english word","translit":"Angliyskoye slovo","src_translit":""}], "src":"en","server_time":69}

and parse it:

Function jsonDecode(jsonString As Variant)
    Set sc = CreateObject("ScriptControl"): sc.Language = "JScript"
    Set jsonDecode = sc.Eval("(" + jsonString + ")")
End Function

Set arr = jsonDecode(txt)

In result arr contains values like below (checked at Watches):

arr
 - sentences (type: Variant/Object/JScriptTypeInfo)
  - 0 (type: Variant/Object/JScriptTypeInfo)
    - orig (type: Variant/String)
    - trans (type: Variant/String)
    ...
  - Item 1 (type: Variant/Object/JScriptTypeInfo)
    - orig (type: Variant/String)
    - trans (type: Variant/String)
    ...
 - server_time
 - src

arr.src works well, but how can I get arr.sentences(0).trans? Firstly, VBA replaces sentences with Sentences, secondly (when I've tried to change the json manually) it still doesn't allow to use sentenses(0).

share|improve this question
    
possible duplicate of Parsing JSON in Excel VBA Look at first answer – Daniel Oct 14 '13 at 12:48
    
1  
@DanielCook, my Excel 2010 doesn't recognize ScriptControl from that answer. – LA_ Oct 15 '13 at 5:10
    
Right, instead of using Private ScriptEngine As ScriptControl put Private ScriptEngine as Object and instead of Set ScriptEngine = New ScriptControl put Set ScriptEngine = CreateObject("ScriptControl") otherwise add the reference indicated in the notes in the answer. This is simply the difference between early and late binding. Either add the reference or update so you don't need it. – Daniel Oct 15 '13 at 12:42
1  
Note that the above approach makes the system vulnerable in some cases, since it allows the direct access to the drives (and other stuff) for the malicious JS code via ActiveX's. Let's suppose you are parsing web server response JSON, like JsonString = "{a:(function(){(new ActiveXObject('Scripting.FileSystemObject')).CreateTextFile(‌​'C:\\Test.txt')})()}‌​". After evaluating it you'll find new created file C:\Test.txt. So JSON parsing with ScriptControl ActiveX is not a good idea. Check the update of my answer for the RegEx-based JSON parser. – omegastripes Oct 26 '15 at 20:00

I hope that the the following library can help you:

https://code.google.com/p/vba-json/issues/attachmentText?id=15&aid=150001000&name=jsonlib.cls&token=bzcFgbVHSfyx0aEDmmt70McRqd4%3A1367585799494

Below some sample code that I used for a project before and that illustrates how to use the library. The library returns a collection object with nested dictionary. I solved the problem by looping through the collection / dictionary to get the things I needed done.

Dim oContracts                      As Collection
Dim oContract                       As Object
Dim vItem                           As Variant
Dim vArray_Contracts                As Variant

Dim JSONlib                         As New c_JSONLib 'class name you give it 
Dim json                            As String

Dim lCnt                            As Long


'Get the returned json
json = request.Response
'Parse the returned json
Set oContracts = JSONlib.parse(CStr(json))

'Count number of parents in the collection
lContract_count = oContracts.Count

If lContract_count = 0 Then
    MsgBox "No contract were found", vbOKOnly
    Exit Sub
End If

ReDim vArray_Contracts(1 To contract_max_rows, 1 To lContract_count)

lCnt = 0
'Get all data from json array
For Each oContract In oContracts
    lCnt = lCnt + 1
    For Each vItem In oContract.keys

        'Underscores since the array cannot contain values with spaces

        Select Case vItem

            Case "local_contr_nr"
                vArray_Contracts(row_local_contract_nr, lCnt) = Replace(nz(oContract(vItem)), " ", "_")

            Case "renewal_date"
                vArray_Contracts(row_renewal_contract_date, lCnt) = Replace(nz(oContract(vItem)), " ", "_")

            Case "contract_name"
                vArray_Contracts(row_contract_name, lCnt) = Replace(nz(oContract(vItem)), " ", "_")

            Case "insurer_name"
                vArray_Contracts(row_insurer_name, lCnt) = Replace(nz(oContract(vItem)), " ", "_")

        End Select

    Next vItem
Next
share|improve this answer
2  
Now it is github.com/VBA-tools/VBA-JSON – Nicholas DiPiazza Mar 13 '16 at 18:04
1  
The question title specifically mentions that they did not want to use external libraries. I'm in a similar boat, and this answer isn't particularly helpful. – Taylor Ostberg Dec 15 '16 at 20:39
    
@TaylorOstberg How does that make sense? An utility library will just provide you with code you would otherwise write yourself. – Kim Gysen Dec 17 '16 at 18:15

Using JavaScript features of parsing JSON, on top of ScriptControl, we can create a parser in VBA which will list each and every data point inside the JSON. No matter how nested or complex the data structure is, as long as we provide a valid JSON, this parser will return a complete tree structure.

JavaScript’s Eval, getKeys and getProperty methods provide building blocks for validating and reading JSON.

Coupled with a recursive function in VBA we can iterate through all the keys (up to nth level) in a JSON string. Then using a Tree control (used in this article) or a dictionary or even on a simple worksheet, we can arrange the JSON data as required.

Full code here : JSON Parser in VBA

share|improve this answer

I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):

    Sub getData()

    Dim Movie As Object
    Dim scriptControl As Object

    Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
    scriptControl.Language = "JScript"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
        .send
        Set Movie = scriptControl.Eval("(" + .responsetext + ")")
        .abort
        With Sheets(2)
            .Cells(1, 1).Value = Movie.Title
            .Cells(1, 2).Value = Movie.Year
            .Cells(1, 3).Value = Movie.Rated
            .Cells(1, 4).Value = Movie.Released
            .Cells(1, 5).Value = Movie.Runtime
            .Cells(1, 6).Value = Movie.Director
            .Cells(1, 7).Value = Movie.Writer
            .Cells(1, 8).Value = Movie.Actors
            .Cells(1, 9).Value = Movie.Plot
            .Cells(1, 10).Value = Movie.Language
            .Cells(1, 11).Value = Movie.Country
            .Cells(1, 12).Value = Movie.imdbRating
        End With
    End With

End Sub
share|improve this answer

in the above example - replacing [ and ] with ( and ) seems to work. Although this is not strictly JSON format anymore.

Then reference it with arr.sentences.trans

Please note I changed mine to sentences2 as Sentences seems to be reserved for an inbuilt property.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.