SPLIT the Address thru SQL in MS ACCESS (1 Viewer)

Rosana

New member
Local time
Yesterday, 20:49
Joined
Aug 25, 2017
Messages
9
Hi,
I have a field with multiple values in it(for ex: address with street,state,zip etc) which is in JSON format. I need to split this into multiple fields. Some of the columns may have multiple addresses also. Those needs to be created in a new row. any ideas would be appreciated.:banghead:

Address
"[
{
""street"": ""678 Willedrobe Dr."",


""state"": ""MI"",
""zipcode"": ""34567"",


""city"": ""Indiana""
}
]"

Thanks
Rosana
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 11:49
Joined
May 7, 2009
Messages
19,246
here i made a Class just for you.
import the Class in your Class Module in VBE.

to call, create first an instance of the class
then parse the json string:

Dim strJson as string
dim json as clsJSON
Dim var As Variant
Dim i As Integer

strJson = "[{""street"":""678 Willdrobe Dr."",""state"":""MI"",""zipcode"":""34567"",""city"":""Indiana""}]"
json = New clsJSON

json.Parse(strJson)

For i = 0 to json.Count-1
debug.print "Fieldname: " & json.Column(i) & ", Value: " & json.Item(i)
Next
 

Attachments

  • clsJSON.zip
    1.2 KB · Views: 60

Rosana

New member
Local time
Yesterday, 20:49
Joined
Aug 25, 2017
Messages
9
Thanks arnelgp.
Where do I call this class? On address field from design view? I am a beginner and please excuse if its an obvious question.
How about strJson with multiple array items? How to insert a new row based on the unique id? My source is a query(join of 3 tables) and not a table.
 

Rosana

New member
Local time
Yesterday, 20:49
Joined
Aug 25, 2017
Messages
9
I am getting this error.
Object variable or With block variable not set

Here is how I am calling.

Option Compare Database
Public Function accessJsonCopy(strJson As String)
Dim json As clsJSON
Dim var As Variant
Dim i As Integer
json = New clsJSON
json.Parse (strJson)
For i = 0 To json.Count - 1
Debug.Print "Fieldname: " & json.Column(i) & ", Value: " & json.Item(i)
Next
End Function

Thanks.
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 11:49
Joined
May 7, 2009
Messages
19,246
It's late here and we have time difference. I'll give u an example dB tomorrow. By the way, I modified some code too handle multiple address.
Goodnyt.
 

Rosana

New member
Local time
Yesterday, 20:49
Joined
Aug 25, 2017
Messages
9
Awesome. I'd appreciate it greatly.
Good Night.
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 11:49
Joined
May 7, 2009
Messages
19,246
here is you sample.
actually my first attempt to create
this parser. and there is no guarantee
it will work at all. only able
to test on small set data.

try to study the code behind form Form1.
 

Attachments

  • agpJsonSample.zip
    40.8 KB · Views: 52

Rosana

New member
Local time
Yesterday, 20:49
Joined
Aug 25, 2017
Messages
9
Thanks a ton arnelgp.
Very well written. I see you have put the parsed values into a new table called tblMain.
Is there a possibility that we can append these parsed values into a query directly instead of table?
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 11:49
Joined
May 7, 2009
Messages
19,246
Sorry, I'm not sure if it is possible.
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 11:49
Joined
May 7, 2009
Messages
19,246
You see, these are only address.
i don't see any unique key of Names that can
connect to your existing query.

if you have a table with Names and json file that Has
corresponding name in the table,
then perhaps, hope is not really lost.

but in order to do this, we have make a temporary
table to add those parsed addresses.
the table can be created using disconnected ADODB.Recordset
so that it will not bloat your database.
and you need a form to show your query.
while the form is loading, we are parsing the json
on the background.

but then again, this are all possibilities.
 

Rosana

New member
Local time
Yesterday, 20:49
Joined
Aug 25, 2017
Messages
9
Thanks arnelgp.
Yes, I do have a unique id field and a full name field in the query.
 

isladogs

MVP / VIP
Local time
Today, 04:49
Joined
Jan 14, 2017
Messages
18,258
actually my first attempt to create
this parser.

Many thanks for this sample file arnel.
It may have been your first attempt but it was very clever.

I had spent several unsuccessful hours trying to parsing an array containing currency exchange rates.
After reading your code here, I've done a modified version for my own purposes & it works perfectly.
I didn't use the rest of your class module as I'd already done the rest of the processing.

For info, attached are the JSON file & my code - including your section (the bit with the Step 2)
I may be able to tidy it up further but will reuse the same idea on other JSON files with arrays

Code:
Public Function TransformCurrencyExchange()

On Error GoTo Err_handler

    Dim rates As Variant ', value As Variant, quotes As Variant
    Dim strTemp As String
    Dim lngStart As Long
    Dim lngEnd As Long
    
    Dim strBase As String
    Dim dteDate As Date
    
    Dim arrFieldsValues As Variant, var As Variant, arrTemp As Variant
    
    Dim arrFields() As String
    Dim arrValues() As Variant
    
    Dim blnFirst As Boolean
    Dim lngCount As Long
        
'get start time
    Start = Timer

ReadJSON:
    'Read .json file
    Set JsonTS = FSO.OpenTextFile(strFilePath, ForReading, False, 0)
    strJSON = JsonTS.readall
     JsonTS.Close
     
ModifyJSON:
    'add dummy text to make parsing easier
    strJSON = "{""result"":[" & strJSON & "]}"
    
   ' Debug.Print strJSON
   
    If InStr(strJSON, """rates"":") = 0 Then
        FormattedMsgBox "The JSON file does not contain valid exchange rate data" & _
            "@ ================================================================                   " & vbNewLine & _
            "ERROR MESSAGE: " & vbNewLine & vbNewLine & Replace(strJSON, """", "'") & "    " & vbNewLine & _
            "================================================================                   " & vbNewLine & vbNewLine & _
            "CHECK the status of your CurrencyExchange key online           @", vbCritical, "Download error"
        
        Exit Function
    End If
    
    N = DCount("*", "tblCurrencyExchange")
        
    If N > 0 Then
        'delete existing records to prevent duplicates
        CurrentDb.Execute "DELETE tblCurrencyExchange.* FROM tblCurrencyExchange;"
    End If
    
    'write to table
    Set db = CurrentDb
    Set rst = db.OpenRecordset("tblCurrencyExchange", dbOpenDynaset, dbSeeChanges)
    
    'Set JSON = JsonConverter.ParseJson(http.responseText)
    Set JSON = modJsonConverter.ParseJson(strJSON)
    
  '  i = 1
    
    With rst
        For Each result In JSON("result")
            strBase = result("base")
            dteDate = result("date")
        Next
                
        '==================================================
        'get string in array
        lngStart = InStr(1, strJSON, """rates""") + 9
        lngEnd = InStr(lngStart, strJSON, "}")
        strTemp = Mid(strJSON, lngStart, lngEnd - lngStart)
        
        Debug.Print strTemp
        
        'parse string in array
        'Thanks to arnelgp @AWF for suggesting this approach
        arrFieldsValues = Split(strTemp, ",")
        
        For Each var In arrFieldsValues
             var = Replace(var, """", "")
             Debug.Print var
             arrTemp = Split(var, ":")
        
        
            For i = 0 To UBound(arrTemp) Step 2
                'remove extra spaces
                 arrTemp(i) = Trim(arrTemp(i))
                 arrTemp(i + 1) = Trim(arrTemp(i + 1))
                 
                 If Not blnFirst Then
                    If lngCount = 0 Then
                        ReDim Preserve arrFields(UBound(arrFields) + 1)
                        ReDim Preserve arrValues(UBound(arrValues) + 1)
                    End If
                Else
                    blnFirst = False
                End If
                
                If lngCount = 0 Then
                    arrFields(UBound(arrFields)) = arrTemp(i)
                    arrValues(UBound(arrValues)) = arrTemp(i + 1)
                End If
                
                .AddNew
                !Currency = arrTemp(i)
                !Rate = arrTemp(i + 1)
                !Base = strBase
                !DownloadDate = dteDate
              '   Debug.Print i, "Currency = " & arrTemp(i), "Rate = " & arrTemp(i + 1)
                .Update
                
            Next i
        Next
        
        lngCount = UBound(arrFields)
        'Debug.Print lngCount
        
        Erase arrFieldsValues
        Erase arrTemp
            
        '===================================================
     ' Next
      .Close
    End With
    
    'Set arrTemp = Nothing
    Set rst = Nothing

   'calculate time taken
    Finish = Timer
    TimeTaken = Finish - Start
    
    CalculateTimeTaken

    'count records
    N = DCount("*", "tblCurrencyExchange")
    '=====================
    If N > 0 Then
        Forms!frmMain.lblInfo.Caption = N & " new exchange rate records " & _
            " added to table " & strTableName & vbNewLine & strTimeTaken
    Else
        Forms!frmMain.lblInfo.Caption = "New exchange rate records " & _
            " were not added to table " & strTableName & vbNewLine & strTimeTaken
    End If

Exit_Handler:
    Exit Function

Err_handler:
    If Err = 9 Then Resume Next
    MsgBox "Error " & Err.Number & " in TransformCurrencyExchange procedure: " & Err.Description, vbExclamation, "Program error"
    Resume Exit_Handler

End Function

I've done an exception for error 9 as I got a subscript out of range error - any idea why? It works fine if I just ignore the error

{"base":"GBP","date":"2017-09-01","rates":{"AUD":1.6314,"BGN":2.1241,"BRL":4.0644,"CAD":1.6106,"CHF":1.2426,"CNY":8.4914,"CZK":28.321,"DKK":8.078,"HKD":10.13,"HRK":8.0603,"HUF":331.35,"IDR":17241.0,"ILS":4.6266,"INR":82.898,"JPY":142.59,"KRW":1450.3,"MXN":23.091,"MYR":5.5285,"NOK":10.052,"NZD":1.807,"PHP":66.142,"PLN":4.6056,"RON":4.9919,"RUB":74.746,"SEK":10.294,"SGD":1.7536,"THB":42.942,"TRY":4.4508,"USD":1.2946,"ZAR":16.745,"EUR":1.0861}}
 

Attachments

  • CurrencyFix.zip
    451 bytes · Views: 54
Last edited:

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 11:49
Joined
May 7, 2009
Messages
19,246
here is your file buddy.
i only parsed the data.
it's up to you to analyze how
you will save that to the table.
i think it is not very hard.
 

Attachments

  • json.zip
    56.4 KB · Views: 52

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 11:49
Joined
May 7, 2009
Messages
19,246
Ms Rossana,

If you can upload a dB with names and your json file with names also, I would like to give it a try.
 

isladogs

MVP / VIP
Local time
Today, 04:49
Joined
Jan 14, 2017
Messages
18,258
here is your file buddy.
i only parsed the data.
it's up to you to analyze how
you will save that to the table.
i think it is not very hard.

Hi arnel

Thanks for your efforts.

However, if you read my last post again, you'll see that I had already parsed and saved the data to a table in Access.
The date is different as I downloaded it again on 1st Sept



My approach is to import to tables - preferably normalised.
The base & date columns could be omitted but I decided to use them.

In my last post, I was actually asking about getting error 9 when parsing the array.

Also, your solution wouldn't really help anyone work with the imported JSON data.



Even if a user wants a listbox they would need 2 columns for the currency & exchange rate.

I hope this reply doesn't sound ungrateful
Thanks for your time
 

Attachments

  • arnelCapture.PNG
    arnelCapture.PNG
    22.9 KB · Views: 146
  • CR_Capture.PNG
    CR_Capture.PNG
    41.7 KB · Views: 155
Last edited:

Users who are viewing this thread

Top Bottom