Developing a LoadRunner script to extract JSON data

I am currently working on creating a loadrunner 'js' file to extract specific data from a json file. The json file is hosted on a web server, which is not causing any issues in retrieving the data. However, my challenge lies in returning a particular value from the json text. I have made an attempt to achieve this on a local html page as shown below, but unfortunately, I keep encountering an error message:

Error encountered: TypeError: Cannot read property 'Location' of undefined

Here is the code snippet used:

<!doctype html> <head></head><script>

function getdata() 
{
var jsontext = '{"Locations":{"Location":[{"@id":"3649","@latitude":"51.758","@longitude":"-1.576","@country":"England","@zoomLevel":"10","@obsZoomLevel":"5","@type":"Observing Site","@name":"Brize Norton","@geohash":"gcnyknk2h"},{"@id":"3","@latitude":"50.9503","@longitude":"-1.3567","@country":"England","@zoomLevel":"11","@type":"Airport and Heliport","@name":"Southampton    Airport","@geohash":"gcp1c5hp4"}]}}';
var stringifiedjson = JSON.stringify(jsontext).replace(/@/g, '_'); //convert to JSON string
var data = JSON.parse(stringifiedjson);
json.innerHTML=data;

try{
var newlocation0 = data.Locations.Location[1]._id;
output.innerHTML=newlocation0;
return;

}
 catch(err){
    message.innerHTML = "(1)Error encountered - " + err;
}

try{
var newlocation0 = data.Locations.Location[1]._id;
output.innerHTML=newlocation0;
return;
}
 catch(err) {
        message.innerHTML = message.innerHTML + "(2)Error encountered - " + err;
    }

try{
var newlocation0 = data.Locations.Location[0]._id;
output.innerHTML=newlocation0;
return;
}
 catch(err) {
        message.innerHTML = message.innerHTML + "(3)Error encountered - " + err;
    }
}
</script>  
<body>
Error Messages:
<p id="message"></p>
<BR><BR>
JSON Input:
<p id="json"></p>
<BR><BR>
Output:
<p id="output"></p>



<button onclick="getdata()">Check</button> 
<button onclick="location.reload();">Reload</button> 

</body>

I have experimented with different notations such as [0] and [1], yet I am unable to get the desired output from the json content.

Answer №1

Initially, the variable jsontext holds a string

var jsontext = '{"Locations":{"Location":[{"_id":"3649","_latitude":"51.758","_longitude":"-1.576","_country":"England","_zoomLevel":"10","_obsZoomLevel":"5","_type":"Observing Site","_name":"Brize Norton","_geohash":"gcnyknk2h"},{"_id":"3","_latitude":"50.9503","_longitude":"-1.3567","_country":"England","_zoomLevel":"11","_type":"Airport and Heliport","_name":"Southampton Airport","_geohash":"gcp1c5hp4"}]}}';

The original string is then wrapped in another string

var stringifiedjson = JSON.stringify(jsontext).replace(/@/g, '_');

The resulting modified string is as follows

\"{\"Locations\":{\"Location\":[{\"_id\":\"3649\",\"_latitude\":\"51.758\",\"_longitude\":\"-1.576\",\"_country\":\"England\",\"_zoomLevel\":\"10\",\"_obsZoomLevel\":\"5\",\"_type\":\"Observing Site\",\"_name\":\"Brize Norton\",\"_geohash\":\"gcnyknk2h\"},{\"_id\":\"3\",\"_latitude\":\"50.9503\",\"_longitude\":\"-1.3567\",\"_country\":\"England\",\"_zoomLevel\":\"11\",\"_type\":\"Airport and Heliport\",\"_name\":\"Southampton    Airport\",\"_geohash\":\"gcp1c5hp4\"}]}}"\"    

By parsing once, the inner JSON string can be extracted

var data = JSON.parse(stringifiedjson);

To obtain the object from the string, parse it again

data = JSON.parse(data);

Alternatively,

There is no need for JSON.stringify initially; the replace method can be used directly.

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

Implementing code to scroll and play multiple videos simultaneously using JavaScript and jQuery

This solution currently only works for one video, but it needs to be able to handle multiple videos (TWO OR MORE) <html> <head> <script src="https://code.jquery.com/jquery-1.8.0.min.js" integrity="sha256-jFdOCgY5bfpwZLi ...

What are some ways to manipulate and work with extensive JSON data using pandas?

I am currently working with a 200mb txt file that contains approximately 25k JSON files, consisting of metadata and content from newspaper articles. My goal is to reduce the size of the file by keeping only the relevant data for my analysis, specifically t ...

AngularJs monitoring changes in service

Why does changing the message in the service not affect the displayed message in 1, 2, 3 cases? var app = angular.module('app', []); app.factory('Message', function() { return {message: "why is this message not changing"}; }); app ...

How can I retrieve the array data that was sent as a Promise?

I have a database backend connected to mongoDB using mongoose. There is a controller that sends user data in a specific format: const db = require("../../auth/models"); const User = db.user const addProduct = (req, res) => { User.findOne({ ...

The Chrome extension functions properly when the page is refreshed or loaded, but it does not work with internal navigation

When landing on a YouTube page starting with w*, I have a script that triggers an alert with the URL. However, this only works when entering the page directly or upon refreshing. I am trying to make the alert trigger when navigating internally to that page ...

Ways to extract information immediately after using the .load method

Is there a way to instantly store data from .load in JavaScript? Whenever I use .load within a JavaScript function to retrieve content from the server and display it on the browser page, the content does not update immediately. It's only when the fu ...

Error: Unable to retrieve image from JSON web service

After creating a JSON web service for saving profile data along with an image, I encountered an issue where the HttpWebRequest would return "The remote server returned an error: NotFound" when sending data to the service. Here is a snippet of the relevant ...

Is it possible to build a Node.js (Express) application using a combination of JavaScript and TypeScript?

Currently, I have a Node.js project (Express REST API) that is written in JavaScript. My team and I have made the decision to gradually rewrite the entire project into TypeScript. Is it possible to do this incrementally, part by part, while still being ab ...

What is the best way to extract data from a textarea HTML tag and store it in an array before iterating through it?

I have a project in progress where I am developing a webpage that will collect links from users and open each link in a new tab. I am using the <textarea> tag in HTML along with a submit button for link collection. Users are instructed to input only ...

jQuery 1.6.2 is compatible with the Android 2.1 emulator, but it does not function properly on the Samsung Galaxy

Has anyone experienced issues with using jquery-1.6.2.min.js on a Samsung Galaxy S with Android 2.1? If so, does anyone know how to modify it to make it work on this device? I recently created a mobile version of a javascript-based website that worked wel ...

What methods can be used to perform unit testing on a controller within an AngularJS Directive?

My command is: window.map.directive('dosingFrequencies', [ function() { return { restrict: 'E', scope: true, templateUrl: '/views/directives/dosingFrequencies.html', controller: function($scope, ...

The analytics event code is visible in the source code, but is not displaying in the console

I am facing an issue with a website built on Umbraco and it has me completely stumped. I have set up event tracking for Analytics on several download buttons, and while most of them are functioning properly, there is one button causing me trouble. When I ...

Understanding the functionality of a notification system

Planning to create an admin tasking system utilizing PHP, MySQL, and JavaScript. Curious about how the notification system operates and how it stores real-time data. Are there any good examples of a notification system? ...

Something seems off with the color of the getImageData when using Fabric JS getContext('2d')

Website: Currently, I am working on adding an eye dropper feature to my website. It functions perfectly at a resolution of 1080p, but when tested on higher or lower resolutions, it malfunctions. Here is the basic code snippet: var ctx = canvas.getContex ...

The express route parser is incorrectly detecting routes that it should not

I am encountering an issue with the following two routes: router.get('/:postId([0-9]*)', handler) router.get('/:postId([0-9]*)/like', handler) The first route is intended to only capture URLs like /posts/4352/, not /posts/3422/like. ...

Transferring data between PHP and JS: when handling large volumes of information

Currently, I am developing a web application that contains an extensive amount of data in the database - we're talking millions upon millions of entries. When it comes to displaying this vast amount of data in a table format with navigation and filter ...

Upon transitioning between router pages, an error message pops up saying "Vue Socket.io-Extended: this.$socket.$subscribe is not a

I have created a basic Vue application that is designed to connect to a NodeJS server using websockets. My setup involves the use of socket.io-extended for handling the connections. After following the documentation and implementing the websocket connect ...

What could be causing the computed property in Vue 2 component to not return the expected state?

I'm encountering an issue with my Vue component where it fails to load due to one of its computed properties being undefined: Error: Cannot read properties of undefined (reading 'map') Here is the snippet of the computed property causing ...

Is there a way to extract the language of an Instagram post using an API

Currently, I am utilizing the specified URL to extract the trending images/videos from Instagram (using PHP). https://api.instagram.com/v1/media/popular?client_id=CLIENT-ID Although this URL returns a JSON object, it does not provide any information abou ...

Converting an object with nested arrays into its original form (Ajax request using C#)

I am struggling with the deserialization of an object that has two properties. One property is a simple string, while the other property is an array of arrays, with each element in an array having a name and a value. The POST operation works fine until it ...