What is the best way to extract information from a JSON object?

I am currently utilizing the JSON.js library provided by JSON.org.

<%
JSONReturn = GetDistance(Sample) // this function returns a string in JSON format (specifically from the ArcGIS server Solve Route function)

JSONObject = JSON.parse(JSONReturn,"Total_Length")
%>

I am attempting to extract the "total_length" data from the JSON object. Could someone please advise me on how I can achieve this?

This is what GetDistance Return:

{
  "routes" : {"spatialReference" : {
      "wkid" : 4326
    }, 

    "features" : [
      {
        "attributes" : {
          "ObjectID" : 1, 
          "Name" : "Location 1 - Location 2", 
          "FirstStopID" : 1, 
          "LastStopID" : 2, 
          "StopCount" : 2, 
          "Total_Length" : 0.498263273388147, 
          "Shape_Length" : 0
        }, 
        "geometry" : null
      }
    ]
  }, 
  "messages" : [
  ]

}

Answer №1

Give this a try.

<%@ Language=VBScript %>
<script language="JavaScript" runat="server">
/**************
Original content available at : https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js
***************/
var json_parse=(function(){"use strict";var at,ch,escapee={'"':'"','\\':'\\','/':'/',b:'\b',f:'\f',n:'\n',r:'\r',t:'\t'},text,error=function(m){throw{name:'SyntaxError',message:m,at:at,text:text};},next=function(c){if(c&&c!==ch){error("Expected '"+c+"' instead of '"+ch+"'");}ch=text.charAt(at);at+=1;return ch;},number=function(){var number,string='';if(ch==='-'){string='-';next('-');}while(ch>='0'&&ch<='9'){string+=ch;next();}if(ch==='.'){string+='.';while(next()&&ch>='0'&&ch<='9'){string+=ch;}}if(ch==='e'||ch==='E'){string+=ch;next();if(ch==='-'||ch==='+'){string+=ch;next();}while(ch>='0'&&ch<='9'){string+=ch;next();}}number=+string;if(!isFinite(number)){error("Invalid number");}else{return number;}},string=function(){var hex,i,string='',uffff;if(ch==='"'){while(next()){if(ch==='"'){next();return string;}else if(ch==='\\'){next();if(ch==='u'){uffff=0;for(i=0;i<4;i+=1){hex=parseInt(next(),16);if(!isFinite(hex)){break;}uffff=uffff*16+hex;}string+=String.fromCharCode(uffff);}else if(typeof escapee[ch]==='string'){string+=escapee[ch];}else{break;}}else{string+=ch;}}}error("Invalid string");},white=function(){while(ch&&ch<=' '){next();}},word=function(){switch(ch){case't':next('t');next('r');next('u');next('e');return true;case'f':next('f');next('a');next('l');next('s');next('e');return false;case'n':next('n');next('u');next('l');next('l');return null;}error("Unexpected '"+ch+"'");},value,array=function(){var array=[];if(ch==='['){next('[');white();if(ch===']'){next(']');return array;}while(ch){array.push(value());white();if(ch===']'){next(']');return array;}next(',');white();}}error("Invalid array");},object=function(){var key,object={};if(ch==='{'){next('{');white();if(ch==='}'){next('}');return object;}while(ch){key=string();white();next(':');if(Object.hasOwnProperty.call(object,key)){error('Duplicate key "'+key+'"');}object[key]=value();white();if(ch==='}'){next('}');return object;}next(',');white();}}error("Invalid object");};value=function(){white();switch(ch){case'{':return object();case'[':return array();case'"':return string();case'-':return number();default:return ch>='0'&&ch<='9'?number():word();}};return function(source,reviver){var result;text=source;at=0;ch=' ';result=value();white();if(ch){error("Syntax error");}return typeof reviver==='function'?(function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}return reviver.call(holder,key,value);}({'':result},'')):result;};}());
</script>
<%
'JSONReturn = GetDistance(Sample) // return a string in JSON format (Arcgis server Solve route function)
Dim JSONReturn, JSONObject
JSONReturn = "{""TotalLength"" : 123}" 'Test
Set JSONObject = json_parse(JSONReturn)
Response.Write(JSONObject.TotalLength) 'Displays "123"
Set JSONObject = Nothing
%>

Answer №2

To access different properties of a JSON object, simply use dots to separate them just like you would with any other object.

For example, in this case:

JSONObject.routes.features[0].attributes.Total_Length

The expression features[0] indicates the first item in the array, but depending on your data structure, you may need to iterate through it in a loop.

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

Explore the inner workings and file contents of a package using the NPM registry API, by accessing a detailed JSON response

Can the NPM registry API be utilized to access an endpoint like https://registry.npmjs.org/jquery And examine the Tarbells structure and internal files without the need to download the package, in a JSON response similar to: { files: { js: registr ...

Navigating through JSON data in Python with a nested for loop

While working on parsing a large JSON in Python, I encountered an issue that is preventing my code from running properly. Specifically, I am parsing the JSON step by step and trying to retrieve the value of all the WHO_REGION attributes for each attr in ...

The TinyMCE editor's input box lost focus while on a popup dialog

Whenever I attempt to access the TinyMCE editor in a dialog box popup and click on "Insert link", the "Insert link" dialog box pops up but I can't type anything into the text field. I suspect that the issue may stem from having a dialog box open with ...

Issue with rendering JSON in Backbone.js -

I am facing a coding challenge: window.TicketCollection = Backbone.Collection.extend({ model:Tickets, url:"/index.php/tickets/viewJSON" }); window.TicketsView = Backbone.View.extend({ tagName:'div', initialize: function () { ...

Breaking down and modifying JavaScript JSON objects

Can someone explain how to separate a JSON object and make updates based on the ID? I've heard about using stringify! But how do I actually implement the function to update the object? <input type="text" value="{"id":"1","price":"30.00","edit":0}, ...

What causes the Vuetify checkbox to trigger twice when clicked in a Vue.js application?

I am facing an issue with a table that contains checkboxes in every row. I want to trigger some logic when a checkbox is clicked. In some cases, I need to tick multiple rows when a checkbox is clicked, so I have set the checkboxes as readonly and handle th ...

Using Python, Scrapy, and Selenium to extract dynamically generated content from websites utilizing JavaScript

I am currently utilizing Python in combination with Selenium and Firefox to extract specific content from a website. The structure of the website's HTML is as follows: <html> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"> ...

Adapting the column width to display or hide content with CSS styling

I have a row with 2 columns. The left column contains my main content and the right column is a chatroom. I would like users to be able to minimize and open the chatroom, which I already know how to do. However, when the chatroom is open, I want the left ...

Utilizing a While Loop for SQL Queries in a Node.js Environment

So, I was attempting to iterate through an array using a while loop. I was able to successfully print a result from the SQL connection without the while loop, confirming that the query is working. However, when I tried to implement the same query within a ...

Issue with AngularJS $scope data binding not working properly inside an iframe element

I find myself in a foreign place.... in my home, why does this happen: Video Url: {{exercise.videos[0].url}} It works correctly by displaying the video url... but: <iframe src="http://fast.wistia.net/embed/iframe/{{exercise.videos[0].url}}"></ ...

When the page is loaded, populate FullCalendar with events from the model

On page load, I am attempting to populate events with different colors (red, yellow, green) on each day of the calendar. Here is a simple example showcasing events for three days: I have data in a model that indicates the available amount of free pallets ...

What is the most efficient way to transfer form data from one JSP page to another?

I need to transfer information from one webpage (1.jsp) to another webpage (2.jsp). The data that needs to be transferred includes checkboxes, radio buttons, and drop downs. This data will be used in 2.jsp to generate the appropriate page. Is there a way ...

Interacting with AngularJS, a C# MVC controller is able to receive a JSON array for processing

Currently, I am in the process of creating a shopping website and have developed a Product model with specific attributes: private string _catalog; [Key] [Required] [RegularExpression("^[0-9]{4}$",ErrorMessage="Catalog number must contain 4 di ...

A guide to sharing session variables with express views

Struggling to access session variables in EJS views and encountering various challenges. To locally access req.session, I've implemented middleware as outlined in this guide on accessing Express.js req or session from Jade template. var express = re ...

Store Form Input as JSON Data File

Seeking advice on the optimal method to save submitted form data to a separate file called data.json, for future reference. The form layout is quite basic: <form> <fieldset> <label for="name">Name:</label> &l ...

Updating a specific field within an array in a Meteor object using MongoDB

I have a document with game details and participants. Here is an example of the structure: { "gameName":"Shooter", "details":[ { "submitted":1415215991387, "author":"XYZ", "subPlayer":{ "members":{ ...

Best practices for aligning the widths of input-group-addon elements

Hey there, I'm working with an HTML file that has 3 input options. Here's a snippet: <script type="text/ng-template" id="dashboard_assigngroup_popup.html"> <div class="modal-header modal-header2"> <h3 class="modal-tit ...

Exploring Django's approach to utilizing primary keys in JSON format

As a newcomer to Django, I am working on retrieving the complete JSON document for the given data model: class Wheels(models.Model): w_name = models.CharField(max_length=255) w_weight = models.IntegerField(default=200) w_size = models.CharField(m ...

How to trigger a JavaScript function when the UI-Router state is switched?

Within my Angular App, I am utilizing ui-router to manage navigation and other tasks. In a separate script file, there is a function that looks like this: $(function () { function doSomething(){ if ($('.thisclass').length) { $(' ...

When the user clicks on an organizational chart, a new organizational chart will appear in a modal popup

Currently, I am developing a project with Highcharts where I have a specific requirement to display a modal popup when a node on an org chart is clicked. The popup should also contain another org chart. Below is the code snippet I am working with: [link to ...