Transforming a sophisticated nested array containing named values into JSON format

I am facing a challenge with converting an array into JSON format. The array, named classProfiles, has the following structure (seen after inspecting console output):

Buildings_clear: Array(0)
  band1: [Min: 24, Max: 24, Mean: 24, Median: 24, StdDev: 0]
  band2: [Min: 22, Max: 23, Mean: 22.5, Median: 22.5, StdDev: 0.5]
  (...)
  __proto__: Array(0)
Grass_clear: Array(0)
  band1: [Min: 17, Max: 24, Mean: 18.61764705882353, Median: 17, StdDev: 2.70092256441423]
  band2: [Min: 13, Max: 21, Mean: 15.441176470588236, Median: 14, StdDev: 2.6030657996088817]
  (...)
  __proto__: Array(0)
Soil_clear: Array(0)
  band1: [Min: 24, Max: 24, Mean: 24, Median: 24, StdDev: 0]
  band2: [Min: 26, Max: 28, Mean: 27, Median: 27, StdDev: 0.816496580927726]
  (...)
  __proto__: Array(0)
length: 0
__proto__: Array(0)

Checking typeof classProfiles in the console returns "object".

However, attempting to convert the array directly to JSON with:

var classProfilesJSON = JSON.stringify(classProfiles)

... results in classProfilesJSON being displayed as "[]".

To address this issue, I tried using jQuery to first convert the array into an object:

var classProfilesObject = $.extend({},classProfiles)
var classProfilesJSON = JSON.stringify(classProfilesObject)

This approach led to classProfilesJSON appearing as:

"{\"Grass_clear\":[],\"Buildings_clear\":[],\"Soil_clear\":[]}"

I am puzzled by this inconsistency. How can I successfully convert this array into a complete and usable JSON format while preserving all the keys and values?

Answer №1

If you're facing a similar issue, I found the solution by rethinking how I was declaring my arrays. Instead of creating arrays, I switched to using objects:

In the sections of my code where I originally had arrays declared like this...

var classProfiles = [];

... I made the necessary changes to declare them as objects like this:

var classProfiles = {};

After making some adjustments in other parts of my code to accommodate the differences between objects and arrays, I was able to successfully convert my objects into JSON.

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

Develop a GWT overlay specifically designed for a deeply nested JSON data structure

Recently stumbling upon this amazing site, I find myself compelled to seek your assistance with a particular issue: How do you go about accessing the fields within the nested JSON object labeled "flightLegs" from the main JSON object "flights"? When it c ...

Is Valums Ajax file Upload capable of handling the uploaded file?

Currently, I am utilizing the Valums Ajax Fileupload script found at These are the settings I have configured: function createUploader(){ var uploader = new qq.FileUploader({ element: document.getElementById('file-uploader-de ...

What might be causing the JSON document to remain partially unused?

I'm experimenting with fetching JSON data from an external source for practice. I've set up all the code, but I keep encountering an error stating that the document is not fully consumed. Despite watching tutorials and reading guides, I can' ...

How do I use Puppeteer to save the current page as a PDF?

Is it possible to convert a web page in a React project to PDF and download it upon clicking a button? ...

Creating a calculator with JQuery and encountering challenges with performing multiple calculations

I've been working on a calculator using jQuery, but I'm encountering issues with the clear button not functioning properly after multiple calculations. On top of that, subsequent calculations are producing inaccurate results. I am seeking to enh ...

Looking for the closest latitude and longitude values in a multi-dimensional array

I am facing a challenging task of searching through a multi-dimensional array to find the closest match based on lat and lon values and return that sub-array. Let's say I have the following preset values: Lat=50.6000, Lon=-74.15000 I need to search ...

Here is a unique version: "In Javascript, users can trigger the function this.Something() from within this.img.onload by

I have some code that looks like this... Thing function () { var img = new Image; DoSomeStuff function() { //Code here that relies on my image being loaded... }; InitMe function(src) { this.img.onLoad = this.DoSomeStuff; ...

Transform an array of arrays object with multiple depths into an array of objects

Having some difficulty with the conversion of an array of arrays-like object into an array of objects. The reduce method is being used, and it successfully converts the array data to an object for the first set of arrays. However, on the second iteration, ...

Issue with uncaught exceptions in promise rejection test

I am experiencing an issue with the following code: function foo(){ bar().catch(function(){ //do stuff } } function bar(){ return promiseReturner().then( function(result){ if(_.isEmpty(result)){ throw "Result is empty"; ...

Modify the current link's <li> class

I am facing an issue with the code below which is supposed to change the class of li based on whether the browser URL matches the href attribute within that li. The current problem I am encountering is that the code changes the class for all li elements, ...

The function contacts.map is not defined

Can someone help me understand why I am getting the error message "contacts.map is not a function"? I am working on fetching data from a contacts array list that I have created. My goal is to display buttons inside a panel. When a button is clicked, the sc ...

Retrieve real-time video information from YouTube

When a user inputs a YouTube video URL into my form, I want to automatically retrieve and display certain information from YouTube such as the title, description, and dimensions of the video. However, I'm struggling to find examples that demonstrate h ...

Angular js: Understanding the use of "this" within the ng-if function

Is there anyone who can assist me with the following question: How do I access the "this" element within the ng-if (in my example, the classname is "class_to_obtain" of the span element)? http://plnkr.co/edit/0s7PCWN2fJ8sJpFSJssV HTML ...

Creating a selectAll checkbox that triggers the ng-click function on each individual checkbox

I've encountered an issue with my code where clicking a checkbox triggers the ng-click function. Here is the JavaScript snippet: $scope.selectTitle = function(evt, selected){ evt.stopPropagation(); var filtered = _.findWhere($scope.se ...

Experiencing difficulties with the onClick functionality on a registration form

Recently started learning React, so I apologize if the solution seems obvious. Currently working on a registration form that should create a new account upon submission using AJAX. Although I understand that I need to use onChange to gather the submitted i ...

What is the best way to extract a specific element from JSON using Angular 2?

Handling a large and complex JSON object stored in a String variable can be tricky. Extracting specific elements, such as series_id and stadium, requires a clear understanding of how to navigate through the data. As a newcomer to angular2, the process mig ...

How can I incorporate a standalone Vuetify component into my Nuxt.js project?

Using Vuetify with nuxt.js specifically for the dashboard layout - how can I achieve this in my nuxt.config.js file? modules: [ //['nuxt-leaflet', { /* module options */}], 'bootstrap-vue/nuxt', '@nuxtjs/ax ...

Allowing several text fields to be paired with multiple checkboxes through a unified jQuery function

I have 4 different checkboxes, each one corresponding to a specific text box. I want to enable the disabled textbox when its corresponding checkbox is checked. Currently, I have written a function for each checkbox in the HTML tag itself using onclick="doc ...

Modifying TextField color in a react application with Material UI

I have a react component that consists of a text field and a button. I want these elements to be displayed in green color on a black background, but I am unable to modify the default colors of all the elements. Following a similar query on how to change th ...

"Exploring the new features of Node.js 14 with ECMAScript modules

When exploring Node's official documentation regarding its built-in support for ECMAScript modules, it is mentioned that There are different types of specifiers: ... Bare specifiers such as 'some-package' or 'some-package/shuffle&apo ...