Having trouble extracting a specific field within a JSON on a webpage using VBA

My current project involves extracting property data from this specified link, which returns a JSON response. I've utilized a combination of JSON and VBA converter tools for this task. However, upon executing the script provided below, I consistently encounter an error labeled as keyNotFoundError. The main goal is to retrieve and process the information under the properties field nested within the features section.

Public Sub parseJson()
    Dim jsonObject As Object, oElem As Variant
    Dim resp$, Url$, R&

    Url = "https://torontolife.com/wp-content/themes/sjm-underscores/inc/neighbourhoods/2015/compiled.json"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", Url, False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36"
        .send
        resp = .responseText
    End With
    
    Set jsonObject = JsonConverter.parseJson(resp)

    For Each oElem In jsonObject("features")
        Debug.Print oElem("properties")
    Next oElem
End Sub

A similar issue persists when attempting the following:

Sub Demo()
    Dim Json As Object
    JsonString = "[{""Entries"":[{""Name"": ""SMTH"",""Gender"": ""Male""}]}]"
    JsonConverter.JsonOptions.AllowUnquotedKeys = True
    Set Json = JsonConverter.ParseJson(JsonString)

    Debug.Print Json(1)("Entries")

Operating on Windows 7 (32 bit), I rely on this specific library for assistance.

It's worth noting that despite the validity of the JSON structure, no challenges surfaced during the parsing phase while utilizing Python.

Answer №1

The reason your code is failing is because the oElem("properties") variable is a dictionary that contains a mix of datatypes associated with the keys. You will need to test each key's type and handle it accordingly. Alternatively, you can use existing programs that can handle this situation by emptying the entire JSON object for you.


Option Explicit

Public Sub ParseJson()
    Dim jsonObject As Object, oElem As Variant
    Dim resp$, Url$, R&

    Url = "https://torontolife.com/wp-content/themes/sjm-underscores/inc/neighbourhoods/2015/compiled.json"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", Url, False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36"
        .send
        resp = .responseText
    End With
    
    Set jsonObject = JsonConverter.ParseJson(resp)
    
    Dim key As Variant, propertyTypes As Scripting.Dictionary
    
    Set propertyTypes = New Scripting.Dictionary
    
    For Each oElem In jsonObject("features")
    
        For Each key In oElem("properties")
           Debug.Print key, vbTab, TypeName(oElem("properties")(key))
           propertyTypes(key) = TypeName(oElem("properties")(key))
        Next

    Next oElem
    'Review propertyTypes dict and/or immediate window print out
    Stop
End Sub

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dealing with the HTTP 413 Request Entity Too Large error within a Node JS Project on Google App Engine

My backend app is currently deployed on GAE. One of the features it offers is an API that allows users to upload files to a GCS bucket. I recently encountered an issue when trying to upload a file larger than 50mb, receiving an error message stating 413 Re ...

Checking the Json response with Java

Can someone help me extract the textType and taxAmount values from the JSON response below? { "taxExempt": false, "billingAddress": { "addressLine1": "Millers Rd", "addressLine2": "", "city": "Bengaluru", "postalCode": "560052", "sta ...

Is it possible to view the object sent from AJAX to PHP in PHP using a debugger?

I'm facing an issue where I am making an AJAX call to a PHP file, sending a JSON object as a parameter from JavaScript. The PHP file is supposed to perform some logic with the object and return it using json_encode('whatever');. However, the ...

Unexpected behavior: JQuery Ajax request not displaying Json object following recent update to JQuery version 1.10.2

Currently facing an issue with a project I am working on. The previous programmer used jquery 1.4.4, and I have updated it to 1.10.2 due to the designer using Bootstrap. However, after running it in version 1.10.2, one of the objects that was functional i ...

VBA Selenium Chromedriver - Issue with SetPreferences not turning off Save As dialog

https://i.stack.imgur.com/yGpGE.pngI have encountered an issue with a program where I am attempting to bypass the SaveAs dialog box when opening a PDF file. Despite using SetPreferences, the dialog box continues to appear. Has anyone successfully disabled ...

What is the best way to parse JSON data received from an Android device using PHP?

I am having an issue with my android emulator where it is sending a request to a PHP script to access MySQL data. I have checked the PHP script by manually giving values to the SQL query and I can retrieve the data in my Android emulator. However, I am fac ...

What are some effective measures to defend against a gzip bomb attack on a service

I have a file named test.gzip which contains JSON data. {"events": [ {"uuid":"56c1718c-8eb3-11e9-8157-e4b97a2c93d3", "timestamp":"2019-06-14 14:47:31 +0000", "number":732, "user": {"full_name":"0"*1024*1024*1024}}]} The full_name field in the JSON data c ...

Scraping multiple websites using NodeJS

I have been immersing myself in learning NodeJS and experimenting with web scraping a fan wikia to extract character names and save them in a json file. I currently have an array of character names that I want to iterate through, visiting each URL in the a ...

Google Chrome is unable to process Jquery JSON .each() function

My website has a simple chat application that is functioning well. It uses ajax to request data in this manner: $.ajax({ url: "fetch/"+CHAT_SESSION_ID+"/"+LAST_MESSAGE_ID, dataType: "json", cache: false, success: function(data) { if (data.session_ac ...

Decoding a Json list with angularJS

I have a JSON dataset structured as follows: $scope.jsondata = [{filename:"/home/username/textfiles/0101907.txt"},{filename:"/home/username/textfiles/0124757.txt"},{filename:"/home/username/textfiles/0747332.txt"} ... ]; Here is my HTML code: <li ng ...

Is it possible to create a pie chart using Chart.js with data fetched through an Ajax HTTP GET

Embarking on a new journey here, this week's focus is on delving into Chartjs for canvas and brushing up on JSON usage. The task at hand includes employing an Ajax HTTP GET request to fetch the json file. However, I am currently stumped on how to trig ...

Perform a JSON POST request from an HTML script to a Node.JS application hosted on a different domain

In an attempt to send string data via a post json request using JavaScript within an .erb.html file, I am facing the challenge of sending it to a node.js app on another domain that uses express to handle incoming requests. After researching online, I have ...

Retrieve JSON data from a WordPress site that is powered by WooCommerce, using basic authentication

I am in the process of creating an Android application that retrieves product data from a WordPress site. The website has the Woocommerce plugin installed. I have been able to successfully obtain the JSON data using Postman software and basic authenticat ...

Comparing JSON data strings on Android with different strings

After fetching data from a MySQL database and displaying it in JSON format, I encountered an issue with comparing strings. According to the logs, all the necessary data is present. try{ JSONArray jArray = new JSONArray(result); for(int i=0;i< ...

Transforming XML into Json using HTML string information in angular 8

I am currently facing a challenge with converting an XML document to JSON. The issue arises when some of the string fields within the XML contain HTML tags. Here is how the original XML looks: <title> <html> <p>test</p> ...

What are some strategies for managing two APIs in a single UIViewController?

I have a single ViewController containing an UIImage and two UITextFields, along with one UITableView. The data to populate these UI elements is fetched from an API. The first API provides the data for the UIImage and UITextFields, while the second API fe ...

Store JSON data in a Python variable

I need to store data from a Json file into separate variables so that I can use them for other purposes. I have successfully created a Json file from inputs in another QDialog. Now, my goal is to extract the inputs from the Json file and assign them to ind ...

Querying a .json document for a specific item and showcasing its price with the help of Discord.js

My current goal is: User inputs !price (item) The bot will look up the item in a JSON file, for example: [ { "hi": 700000, "low": 650000, "name": "football" } ] The bot will then respond with Name: Football High: 6500 ...

Search for JSON keys in the output data stream

Consider this example JSON file: { "mac": "00:11:22:33:44:55", "name: "Test123", "ssid": "29321", "password": "txt", "data": { "test:": "no", "dev": "yes", "prod": false }, "signals": [12, 34, 65, 93, 21 ...

Exploring Angular.js: Finding the correct path in a JSON array

Within my Angular application, I have a $scope variable defined as follows. $scope.roleList2 = [ { "roleName" : "User", "roleId" : "role1", "children" : [ { "roleName" : "subUser1", "roleId" : "role11", "collapsed" : true, "children" : [ ...