How To Import JSON To Excel Using VBA - Excelerator Solutions
How To Import JSON To Excel Using VBA - Excelerator Solutions
to Excel Using VBA How to Import JSON to Excel Using VBA | Excelerator Solutions
Howdee! It’s becoming increasingly more common for data to be generated in a JSON
format as opposed to XML. XML was widely used for years, but recently JSON has
started to become the preferred method of data exchange. Many REST APIs have the
option to return both but the majority that I interact with default to returning JSON
formatted data. Therefore, as excel ninjas, it’s important to understand how to import
JSON to Excel for analysis. Before we begin on that route, let’s take a quick moment to
talk about what JSON is for those that aren’t familiar with it.
What is JSON?
JSON stands for JavaScript Object Notation and is a lightweight data-interchange format.
In layman’s terms, it is a string of text that represents a universal data structure. It is easy
for humans to read (when formatted properly) and, because of the universal structure, it
is very easy and fast for machines to parse and generate. It’s made simple because
JSON, at it’s most basic, is only two data types. It is made up of objects, or arrays, or a
combination of both. Objects are made up of key/value pairs (often called a dictionary)
and arrays are simply collections of values or objects separated by a comma.
It’s important to note that object/dictionary and array are the terminology applicable to
the .NET language. Other languages might have other terminology such as hash table
for object, or vector for an array. This site gives a great high level, cross-language
overview of JSON.
JSON Object
A JSON object always begins with { and ends with }. The key is separated from its value
with a colon (“:”). The key/value pairs will then be separated by commas all within the
curly brackets. In the image below, the rst key “color” corresponds to its value “red”,
while the second key “value” corresponds to the red hex code “#f00”. Hopefully you can
see why this might be called a dictionary as you look up the key (word to de ne) to get
its value (de nition of the word).
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/ 1/15
23/1/2021 How to Import JSON to Excel Using VBA | Excelerator Solutions
JSON Array
A JSON array, in its simplest form, is a list of values separated by a comma that begins
with [ and ends with ]. In the below image, the JSON array is a list of string data points.
We can see that they are colors but there is no key in this example explicitly telling that
this string represents a color. Therefore, JSON is most commonly seen as a combination
of arrays and objects.
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/ 2/15
23/1/2021 How to Import JSON to Excel Using VBA | Excelerator Solutions
In this example, each object represents a color and its corresponding hex code. In Excel,
this would likely be two columns of data. One column for color, and the other for its hex
code value. Now that you’re more familiar with JSON data structure, let’s learn how to
import JSON to Excel!
Once you have completed both steps, insert a new module into your project and title it
whatever you like. To get started, we need to dimension some variables to use later.
Dim ws As Worksheet
Dim jsonText As String
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/ 3/15
23/1/2021 How to Import JSON to Excel Using VBA | Excelerator Solutions
Dim jsonText As String
Dim jsonObject As Object
The ws variable will represent a worksheet in excel. In this example, we will use this
worksheet to both read in our JSON string from and write the parsed JSON to Excel. To
assign a worksheet to this variable, set it like this:
jsonText = ws.Cells(1, 1)
This step is not necessary for the code to work for us. We could simply reference the cell
in the worksheet that contains the JSON. However, most of the time you’ll be returning
your JSON string from another data source, most likely a HTTP GET Web Call. If you’re
not familiar with HTTP Requests in VBA, click here to learn more.
Lastly, to put the JSON string into the jsonObject, we will use one of the methods
contained in the JsonConverter le you imported to begin this example. Since the builder
of this library made all of the subroutines public, it is callable from the module this code
is in. That call looks like this:
Sub JsonToExcelExample()
Dim jsonText As String
Dim jsonObject As Object, item As Object
Dim i As Long
Dim ws As Worksheet
jsonText = ws.Cells(1, 1)
i = 3
ws.Cells(2, 1) = "Color"
ws.Cells(2, 2) = "Hex Code"
End Sub
I set a counter variable, i, that I can use to tell the loop which row to write the data to.
Next, create my column headers for the data. Then, for each “item” in the jsonObject
write that dictionaries values to the cell row I indicate and increment my counter
variable. That’s it! The results of our import JSON to Excel code looks like this:
As you can see, we’ve turned that odd-looking string of text in cell A1 to an easy to
understand table of data with just a few lines of code!
For example, let’s look at an example where the JSON is structured as a single object
with key “data” and the value is an array of data about employee’s and their organizations:
As you can see, we have an object with an array nested inside. Some objects in the array
contains other nested objects as well. This multi-tiered data structure is very common
when pulling data from a REST service and was very confusing to me when I rst began
trying to import JSON to Excel. Let’s examine what the code looks like for this scenario
before we dive any deeper.
Sub JsonToExcelAdvancedExample()
Dim jsonText As String
Dim jsonObject As Object, item As Object
Dim i As Long
Dim ws As Worksheet
jsonText = ws.Cells(1, 1)
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/ 6/15
23/1/2021 How to Import JSON to Excel Using VBA | Excelerator Solutions
i = 3
ws.Cells(2, 1) = "id"
ws.Cells(2, 2) = "Name"
ws.Cells(2, 3) = "Username"
ws.Cells(2, 4) = "Email"
ws.Cells(2, 5) = "Street Address"
ws.Cells(2, 6) = "Suite"
ws.Cells(2, 7) = "City"
ws.Cells(2, 8) = "Zipcode"
ws.Cells(2, 9) = "Phone"
ws.Cells(2, 10) = "Website"
ws.Cells(2, 11) = "Company"
End Sub
The code overall is the exact same, just referencing a di erent tab and added more
elds to pull out. The change I want to point out is to the for loop itself. The beginning of
the for loop now starts by referencing the overall object that contains the array. This is
referred to as the “root” of the JSON and you’ll see it if you’re querying a REST API for
JSON data. This moves the for each loop inside the “data” level of the JSON and will now
loop through all objects in the highest-level array. Had I left this out, the loop would only
occur once as the JSON is all contained within a single object at its top level.
The second piece I want to point out is the lines for address and company. These are
both objects contained within the parent object. So, in order for me to reach to value I
t Ih t f b th k t
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/
t th i l I d L tl I tt ll 7/15
23/1/2021 How to Import JSON to Excel Using VBA | Excelerator Solutions
want, I have to reference both keys to get the speci c value I need. Lastly, I want to call
out that you do not need to write every value from the returned JSON to the sheet. I have
skipped over several elds to get the end result I desired and it does not a ect my code
results, which coincidently look like this:
I hope this brief explanation of how to import JSON to Excel was useful for you! Please
let me know if it was helpful or if you have any questions in the comments below. Also, if
you want to download the le with the example JSON and VBA code, you can do so here
if you’re a free subscriber to the site. It’s free, easy, and only takes a moment to sign up.
Cheers!
12 COMMENTS
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/ 8/15
23/1/2021 How to Import JSON to Excel Using VBA | Excelerator Solutions
BERTRAND CAMBORDE
Posted at 02:40h, 11 December Log in to Reply
Good morning. First thanks a lot for your post. I am trying the rst
example on excel for Mac and don’t succeed to get your code up
and running. First I had to import the Bas le manually because of
excel for mac 2016 not accepting the import of .bas le and I also
had to import a dictionary.cls class module manually since once
again there is no Microsoft Scrpting runtime reference on Mac. I
had to make changes to these codes since it was not working
properly (basically commenting out some parts) so not sure if my
issue is coming from there or somewhere else. I end up with an
execution error 438 on the rst loop of for each item in JsonObject
saying that this property or method is not supported for item I
guess. I have some print screens I can provide if necessary. If you
could help me there that would be great. I looked at the local
variables and don’t see where the issue is coming from. Thanks in
advance for your help
RYAN CLOUSE
Posted at 17:39h, 11 December Log in to Reply
Hi Bertrand, unfortunately the VBA-JSON library will
not work on a mac version of excel. If you need to
transform some JSON there are some links you can
google that will convert a JSON string to a CSV le for
you and you can then import that into your version of
Excel, but I do not believe you’ll be able to use the
methods I outline above on a mac.
MONCHAI PON
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/ 9/15
23/1/2021 How to Import JSON to Excel Using VBA | Excelerator Solutions
RYAN CLOUSE
Posted at 19:31h, 16 March Log in to Reply
Hi M
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/
h i t l d ?Y 10/15
23/1/2021 How to Import JSON to Excel Using VBA | Excelerator Solutions
Hi Monchai – can you post some sample code? You
should be able to follow along in the tutorial and
access your parsed json with keys like (“quotes”)(“2011-
01-03”) to access the last one. The string you posted
also is not formatted as correct JSON so perhaps that’s
the error?
TYLER ROSE
Posted at 06:39h, 16 March Log in to Reply
Quick question: I can access a nested key value pair with the
syntax of item(“address”)(“street”) as from your example, but I
need to get access with a variable and some values will be nested
and others aren’t. For example, I want to access it with a variable
like item(variable1) where I could de ne the “variable1” as “name”
or “address/street” and pull a value.Is this possible? I was able to
do something similar with an XML document, but JSON is giving
me trouble.
RYAN CLOUSE
Posted at 19:28h, 16 March Log in to Reply
Hi Tyler – you should be able to do this by just passing
in the variable that is representing your dictionary
key(s). What type of variable are you storing the
dictionary key as? You’ll probably need to make sure it
is of variant type. Do you have some sample code of
what you’ve tried to get working?
DEAN MILLER
Posted at 17:39h, 21 March Log in to Reply
Hi Ryan, I was hoping you could possibly help.
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/ 11/15
23/1/2021 How to Import JSON to Excel Using VBA | Excelerator Solutions
Thanks,
RYAN CLOUSE
Posted at 17:48h, 21 March Log in to Reply
Hi Dean,
Cheers,
Ryan
DEAN MILLER
Posted at 09:23h, 22 March Log in to Reply
I’ve realised the data I’m using is slightly
di erent to your example.
Where you have the “lat” & “lng” as
additional items in your JSON, in the set I’m
working with, they are stored as a list,
encased is square brackets
RYAN CLOUSE
Posted at 13:55h, 22 March Log in
to Reply
Ahh, yes when you have an array
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/ 12/15
23/1/2021 How to Import JSON to Excel Using VBA | Excelerator Solutions
Cheers!
Ryan
J MANNERS
Posted at 16:12h, 17 April Log in to Reply
I’m aware that this may be cutting in on these wonderful ideas,
however going on what Dean is talking about. I too had the same
problem with the JSON would start o as a new array.. To solve
my problem I did something like the below.
json parse would be;
{“jsonrpc”:”2.0″,”result”:[{“groupid”:”15″,”name”:”TEST
NAME”,”internal”:”0″,” ags”:”0″,”hosts”:
[{“hostid”:”10255″,”name”:”TESTING SERVER ONE”}]}],”id”:1}
Sub GetZabbix()
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/ 13/15
23/1/2021 How to Import JSON to Excel Using VBA | Excelerator Solutions
Dim ws As Worksheet
Dim strJSON As String
Dim strResp As String
Dim jsonText As String
Dim httpReq As New WinHttpRequest
Dim strURL As String
Dim jsonObject As Object, item As Object
Dim i As Long
Dim a As Long ‘ ADDED THIS IN FOR IN LOOP
Dim grpHost As Object ‘ ADDED THIS IN FOR PARSING
RESULTS:HOSTS
httpReq.Option(4) = 13056 ‘
httpReq.Open “POST”, strURL, False
httpReq.SetCredentials “YOUR USER ID”, “PASSWORD”, 0
httpReq.SetRequestHeader “Content-Type”, “application/json-rpc”
httpReq.SetRequestHeader “User-Agent”, “Mozilla/4.0
(compatible; MSIE 6.0; Windows NT 5.0)”
httpReq.Send strJSON
strResp = httpReq.ResponseText
ws.Cells(20, 1) = strResp
‘jsonText = ws.Cells(20, 1)
End Sub
*************
Hope this helps someone out there..
cheers,
J
POST A COMMENT
You must be logged in to post a comment.
excelerator.solutions/2017/08/16/import-json-to-excel-using-vba/ 15/15