Looping through and printing JSON strings

Currently, I am dealing with a JSON string of this specific format:

{"prey":["{\"distance\": 8.686924173343307, \"signal\": \"-59\", \"frequency\": 2447, \"mac\": \"00:00:00:00:00:00\", \"ip\": \"192.168.43.27\"}"]}

To parse this JSON, I am utilizing the following code:

var jsonSpy = JSON.parse(userList);

My goal is to extract the distance value from it using the code provided below. I have tried two different approaches which yield similar results. Although I can successfully output each set of data including distance, signal, frequency, mac, and ip individually, I am facing an issue when attempting to retrieve a particular piece of information as indicated in the code snippet. Despite that both iterations through the loop and using each function seem to produce the same outcome of displaying the JSON string, I encounter a problem specifically when trying to access the 'distance' parameter - instead of an error message, all I get is 'undefined'.

for(var i = 0; i < jsonSpy.prey.length; i++)
{
    console.log(jsonSpy.prey[i]);
    console.log(jsonSpy.prey[i].distance);
    ctx.fillRect(jsonSpy.prey[i].distance, 300, 20, 20);
}

$.each(jsonSpy.prey, function(i, item) {
    console.log(jsonSpy.prey[i]);
    console.log(jsonSpy.prey[i].distance);
    ctx.fillRect(jsonSpy.prey[i].distance, 300, 20, 20);
});

Answer №1

The content in jsonSpy.prey[0] is currently in string form. To make use of the JSON data inside, you must pass it through JSON.parse() once more:

for(var i = 0; i < jsonSpy.prey.length; i++)
{
    var innerJSON = JSON.parse(jsonSpy.prey[i]);

    console.log(jsonSpy.prey[i]);
    console.log(innerJSON.distance);
    ctx.fillRect(innerJSON.distance, 300, 20, 20);
}

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

Why does my jQuery map code work in version 2.0 but not in version 3.0?

I've encountered an error with a jQuery map snippet that I'm trying to troubleshoot. It was working fine under jQuery 2, but after upgrading to version 3, it doesn't work anymore and I can't figure out why. Feeling stuck! var menuIte ...

"Using the selected option from a dropdown list to pass to a PHP file for autocomplete functionality

Although there is no error in the code, I am facing an issue where, after selecting an option from the brands dropdown, when I type in the product field, it passes "%" instead of the brand id (1, 2, or 3). Is there a way to modify the code so that it passe ...

Is it considered a best practice to utilize JavaScript for positioning elements on a

I recently started learning JavaScript and jQuery, and I've been using them to position elements on my website based on screen and window size. It's been really helpful, but I'm starting to wonder if it's a good practice since it makes ...

Tips for accessing image data generated by the Bootstrap File Input plugin

I have a div that utilizes the Bootstrap File Input plugin to select, show, change, and cancel images. The image data is generated dynamically by the plugin. <div class="fileinput fileinput-new" data-provides="fileinput"> <div class="fileinpu ...

The compatibility between Laravel's @vite('resources/js/app.js') and the froala editor plugin seems to be causing issues

I have incorporated a Vue.js based commenting system and inbox messages system in my Laravel website. Additionally, I am utilizing a wysiwyg editor (Froala Editor) in my forms for uploading projects. The issue I am facing is that the Froala Editor does no ...

Having trouble submitting the form in ExpressJS - error encountered

Currently, I am in the process of learning ExpressJS and I have encountered an issue while trying to implement the login functionality. Whenever I attempt to submit the form using the POST method, I receive the following error message: "Cannot POST /login" ...

Every time I run `npm install`, I consistently encounter the `code ECONNREFUSED` error message for every

`npm ERR! code ECONNREFUSED npm ERR! errno ECONNREFUSED npm ERR! FetchError: request to http://registry.npmjs.org/body-parser failed, reason: connect ECONNREFUSED 127.0.0.1:3000` I attempted various solutions such as adjusting proxy settings and running ...

What is the process of integrating an ejs view engine with express on Netlify?

Need help configuring the ejs view engine with netlify I attempted to set app.set('view engine', 'ejs'), but didn't see any results. const express = require('express'); const path = require('path'); const serv ...

There was an issue with processing the information. (The JSON object could not be deserialized properly)

Currently attempting to deserialize a collection of book objects retrieved from the GoogleBook API. Models: https://pastebin.com/24S16hZc API Response Confirmation: https://pastebin.com/2q0aFGnf Booking Page: public BookingPage() { this.I ...

Error in THREE.js: Unable to access property 'lib' from an undefined source (THREE.ShaderUtils.lib["normal"])

I have been working on the challenges provided in the WebGL introductory book by Oreilly. Encountered a runtime error with the following code snippet. After searching online, it seems like I am the only one facing this issue. Could you please assist me in ...

Instructions for including a dropdown/button in CKEditor to input content upon selecting a dropdownItem

I am looking to customize the ckeditor's toolbar by adding a dropdown or button that will display a list. When an item from the list is clicked, I want the text of that item to be inserted into the ckeditor's content. Additionally, I need the ab ...

Can WS Websocket in Swift send and receive JSON objects?

An unhandled exception 'NSInvalidArgumentException' is causing the app to terminate, with the reason being 'Invalid type in JSON write (_NSInlineData)' Define the data variable as the type of data being used Let dictionary : NSDictiona ...

Shut down the pop-up in Chrome before the DOM finishes loading

Utilizing the most recent iteration of the selenium web driver along with the Google Chrome browser, I am encountering an issue in my application. Following the click on the login button, a popup appears while the DOM is still loading. view image I simpl ...

What is the best way to extract the numerical value from a JavaScript object?

I'm currently working on a web form for a currency exchange demonstration. I have included a snippet of HTML and Javascript code that I have initially implemented. <!DOCTYPE html> <html lang="en"> <head> <meta charset="ut ...

Nuxt - Issue persisting logged in state on refresh despite information being stored in local storage and cookies

I am facing an issue where the state gets cleared on refresh, even though the token, userid, user email, and expiration date are stored in local storage and cookies. I suspect there might be a problem with the store or something else needs to be done to re ...

What is the best way to format dates in jQuery AJAX requests?

Utilizing jquery to interact with a REST API in (ASP.net Web API). I've constructed a basic object and then utilized jquery to 'PUT' it on the server: var myObject = { name: 'just a name', createDate: new Date() } $.ajax({ ...

A beginner's guide to implementing dot navigation within the Jackson JsonNode

Take a look at this code snippet: val parsedData = ObjectMapper().readTree(vcap) parsedData.get("spaces")?.firstOrNull()?.get("block1")?.asText() I'm interested in improving the readability of this code by using dot notation for navigation. Here&ap ...

When using the combination of JBoss, RestEasy, and Jackson, you may encounter the error message: "Attempting to cast org.jboss.resteasy.core.ServerResponse to org.jboss.re

I am currently working on a REST Api using JBoss (AS 7.1), RestEasy, and Jackson. The web service returns an "Account" object, which is a simple POJO that was previously serialized in JSON without any issues. However, after making some changes to the code ...

Doing server side function calls from the client in NodeJs

I recently embarked on a journey to learn web development and am eager to make server-side data changes when invoking client functions. Take a look at my sample server setup: const fs = require('fs'); const path = require('path'); con ...

Utilizing external clicks with Lit-Elements in your project

Currently, I am working on developing a custom dropdown web component using LitElements. In the process of implementing a feature that closes the dropdown when clicking outside of it, I have encountered some unexpected behavior that is hindering my progres ...