JSON (Javascript Object Notation) is the most used data exchange format nowadays. Microsoft Excel doesn’t have built-in support for importing JSON to excel or exporting excel data to JSON.
VBA-JSON is an excellent library for parsing JSON in VBA. Lets see how to handle JSON in Excel VBA. If you’re new to JSON then read JSON tutorial for beginners
Prerequisites
- Save your excel file as Macro-Enabled workbook (Refer screen shot below)
- Enable macros if they are not already enabled. You can enable it by cliking on file > options > Trust Center > Trust Center Settings > Enable all macros
Getting Started
- Download VBA JSON latest version from here
- Extract it, open VBA code editor in excel (Alt + F11) and import the library as shown in the gif below.
- Add a reference to Microsoft scripting runtime. (Tools > references > select)
-
Add a reference to MSXML (Tools > references)
Select appropriate version based on your PC :
1. Microsoft XML, v 3.0.
2. Microsoft XML, v 4.0 (if you have installed MSXML 4.0 separately).
3. Microsoft XML, v 5.0 (if you have installed Office 2003 – 2007 which provides MSXML 5.0 for Microsoft Office Applications).
4. Microsoft XML, v 6.0 for latest versions of MS Office.
Import JSON to Excel
This library provides a simple method ParseJson
to parse JSON string into a dictionary object which can be used to extract data. Let’s see an example.
I’m using fake data from http://jsonplaceholder.typicode.com/ which is an API service with fake Json data.
We’ll be pulling user data from http://jsonplaceholder.typicode.com/users by making a GET request which responds with Json data.
Read more about GET requests in VBA here
Next, we’ll parse that Json and import it to excel. Code for importing data looks like this :
Public Sub exceljson() Dim http As Object, JSON As Object, i As Integer Set http = CreateObject("MSXML2.XMLHTTP") http.Open "GET", "http://jsonplaceholder.typicode.com/users", False http.Send Set JSON = ParseJson(http.responseText) i = 2 For Each Item In JSON Sheets(1).Cells(i, 1).Value = Item("id") Sheets(1).Cells(i, 2).Value = Item("name") Sheets(1).Cells(i, 3).Value = Item("username") Sheets(1).Cells(i, 4).Value = Item("email") Sheets(1).Cells(i, 5).Value = Item("address")("city") Sheets(1).Cells(i, 6).Value = Item("phone") Sheets(1).Cells(i, 7).Value = Item("website") Sheets(1).Cells(i, 8).Value = Item("company")("name") i = i + 1 Next MsgBox ("complete") End Sub
Code explanation
- First, define JSON as an object and make a GET request to JSON API
- JSON data received in the response is parsed by passing it into
ParseJson
method. - parsed data is converted into a collection of dictionaries.
- Loop through the collection to get each user’s details and set its values to the first sheet.
Running above code looks like gif below.
Reading JSON from a file
In the same example above, If you want to read JSON data from a local file then you can use FileSystemObject
to read all text in the file and then pass it to ParseJson
method.
Dim FSO As New FileSystemObject Dim JsonTS As TextStream Set JsonTS = FSO.OpenTextFile("example.json", ForReading) JsonText = JsonTS.ReadAll JsonTS.Close Set JSON = ParseJson(JsonText)
Export Excel to Json
VBA-JSON provides another method ConvertToJson
which can be used to convert excel data into JSON. Here’s an example.
Sample data with Name, Phone and Email is present in second sheet. Let’s convert it into JSON
Code for this looks like :
Public Sub exceltojson() Dim rng As Range, items As New Collection, myitem As New Dictionary, i As Integer, cell As Variant set rng = Range("A2:A3") 'Set rng = Range(Sheets(2).Range("A2"), Sheets(2).Range("A2").End(xlDown)) use this for dynamic range i = 0 For Each cell In rng Debug.Print (cell.Value) myitem("name") = cell.Value myitem("email") = cell.Offset(0, 1).Value myitem("phone") = cell.Offset(0, 2).Value items.Add myitem Set myitem = Nothing i = i + 1 Next Sheets(2).Range("A4").Value = ConvertToJson(items, Whitespace:=2) End Sub
Code Explanation
- First, define
rng
as range and set it to data range. ConvertToJson
method takes a dictionary collection or array as parameter. So we should pass our data as a collection.- A Dictionary is an object with keys and values just like JSON but doesn’t support multiple items like arrays or collections, so we create a dictionary for each item and push it into an array or a collection.
- Define a dictionary and a collection, loop through the range and set each row’s data into
myitem
- Push
myitem
into collection and set it to nothing, because we are using the same dictionary to add next row’s data and push it to collection again.
Finally pass items
collection to ConvertToJson
method which returns a JSON string.
Running above code looks like gif below
Export Excel to JSON file
In the same example above, If you want to export excel data to JSON file then It can be done by opening a file for output by specifying the path of the file and printing data in it. Sample code below, Running this would save a JSON file in the current workbook’s folder.
Public Sub exceltojsonfile() Dim rng As Range, items As New Collection, myitem As New Dictionary, i As Integer, cell As Variant, myfile As String Set rng = Range("A2:A3") 'Set rng = Range(Sheets(2).Range("A2"), Sheets(2).Range("A2").End(xlDown)) use this for dynamic range i = 0 For Each cell In rng Debug.Print (cell.Value) myitem("name") = cell.Value myitem("email") = cell.Offset(0, 1).Value myitem("phone") = cell.Offset(0, 2).Value items.Add myitem Set myitem = Nothing i = i + 1 Next myfile = Application.ActiveWorkbook.Path & "\data.json" Open myfile For Output As #1 Print #1, ConvertToJson(items, Whitespace:=2) Close #1 End Sub
Export Excel to Nested JSON
Above code can be modified a bit to get a nested JSON as output. Just add dictionary in another dictionary so that it creates a nested JSON. code looks like this :
Public Sub exceltonestedjson() Dim rng As Range, items As New Collection, myitem As New Dictionary, subitem As New Dictionary, i As Integer, cell As Variant Set rng = Range("A2:A3") 'Set rng = Range(Sheets(2).Range("A2"), Sheets(2).Range("A2").End(xlDown)) use this for dynamic range i = 0 For Each cell In rng Debug.Print (cell.Value) myitem("name") = cell.Value myitem("email") = cell.Offset(0, 1).Value myitem("phone") = cell.Offset(0, 2).Value subitem("country") = cell.Offset(0, 3).Value myitem.Add "location", subitem items.Add myitem Set myitem = Nothing Set subitem = Nothing i = i + 1 Next Sheets(2).Range("A4").Value = ConvertToJson(items, Whitespace:=2) End Sub
Running above code looks like image below
Using array of strings and objects in JSON
One of our readers asked me how to use an array of strings and objects inside the JSON.
Here’s how to do it:
Public Sub exceltojson() Dim rng As Range, items As New Collection, myitem As New Dictionary, i As Integer, cell As Variant, objectContainer As New Dictionary, arrayContainer As New Collection Dim j As Integer 'Set rng = Range("A2:A3") Set rng = Range(Sheets(1).Range("A2"), Sheets(1).Range("A2").End(xlDown)) 'use this for dynamic range i = 0 For Each cell In rng myitem("id") = cell.Value myitem("name") = cell.Offset(0, 1).Value 'tags tagsString = cell.Offset(0, 2).Value tagsCollection = getCollectionFromString(tagsString) myitem.Add "tags", tagsCollection 'ingredients ingredientsString = cell.Offset(0, 3).Value weightsString = cell.Offset(0, 4).Value ingredientsUnit = cell.Offset(0, 5).Value ingredientsCollection = getCollectionFromString(ingredientsString) weightsCollection = getCollectionFromString(weightsString) j = 0 For Each ingredient In ingredientsCollection objectContainer("ingredientnaam") = ingredient objectContainer("eenheid") = ingredientsUnit objectContainer("hoeveelheid") = weightsCollection(j) arrayContainer.Add objectContainer Set objectContainer = Nothing j = j + 1 Next myitem.Add "ingredienten", arrayContainer 'Reset values Set arrayContainer = Nothing j = 0 items.Add myitem Set myitem = Nothing i = i + 1 Next Sheets(1).Range("A6").Value = ConvertToJson(items, Whitespace:=2) End Sub Function getCollectionFromString(val) getCollectionFromString = Split(val, ", ") End Function
Running above code looks like image below
Wrapping up
Read official documentation of VBA-JSON here and use VBA-Dictionary for Mac Support.
Related articles :
- Complete JSON tutorial here – JSON for beginners
- Handling CSV in VBA
If you have any questions or feedback, comment below and please use CodingisLove Bin for sharing your code.