JSON.stringify not behaving as anticipated

I am working on the code below;

var data = [];
data['id'] = 105;
data['authenticated'] = true;
console.log(data);
var jsonData = JSON.stringify(data);
console.log(jsonData);

The initial console.log is displaying;

[id: 105, authenticated: true]

However, the final console.log is just showing an empty array. I would like to convert the array into a json object. Is there something I am overlooking?

Appreciate any help!

Answer №1

It is recommended to define rawData as an Object instead of an array. This way, you can easily add or remove additional attributes as key-value pairs. When converting it back to an Object, make sure to use JSON.parse method.

    var rawData = {};
    rawData['uid'] = 105;
    rawData['auth_customer'] = true;

    console.log(rawData); // Object

    var postData = JSON.stringify(rawData);
    console.log(postData); // String - "{'uid':105,'auth_customer':true}"

    console.log(JSON.parse(postData)); // Object

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

The information within the ajax request remains static

I made changes to my ajax data, saved it and even double-checked the file location. However, the old version is still appearing as if it's cached. Here is the original code: function setMessages(roomId, username, message){ $.ajax({ type: ...

When clicked, the onClick feature will reduce the number each time instead of initiating the timer

Currently, I am working on a meditation application using React. As a starting point, I implemented a 25-minute countdown feature. The challenge I am facing is that the timer starts counting down each time the button is clicked, rather than triggering it ...

The convergence of Phoenix, Json, and Unix Timestamps

Currently, I am in the process of exporting data from SQL Server in json format to be able to import it into my Phoenix app. One aspect that I'm uncertain about is how to handle dates. As of now, I am exporting dates as Unix timestamps. Below is an ex ...

Leveraging Discord.JS to seamlessly transport users in Discord to their designated voice channel by assigning roles

I'm attempting to transfer all users with a specific role from a voice channel using a command like: !summon @role This command should bring only the users with that specific role to the voice channel where the command was entered My current code is ...

Only the initial element within the specified class is targeted by JQuery

Currently, I am utilizing Kendo UI to refresh multiple charts by class without having to access each one individually. Here is the code snippet I am using: $(".k-chart").data("kendoChart").refresh(); The issue I am encountering is that only the first cha ...

Unable to utilize jQuery's .append(data) function due to the need to use .val(append(data)) instead

I have been attempting to utilize JQuery .append(data) on success in order to change the value of an input to the appended data like this: .val(append(data)), but it doesn't seem to be working. Surprisingly, I can successfully change the value to a st ...

How can you target a specific data-target button while working with multiple Bootstrap collapse elements?

One challenge I'm facing is with the Bootstrap collapse elements on my website. I have several of them, each controlled by a read-more button that includes an icon to indicate the state of the collapse element. However, when I add a class to the butto ...

Error: Attempting to access the 'body' property of an undefined object following a POST request in a MEAN application

Currently, I am attempting to send POST data from AngularJS to Express. My approach involves using curl to transmit the POST content. After sending the data and receiving a 200 response, I encounter an issue when trying to access the data through body-par ...

efficient ways to eliminate redundant JSON objects in Python

How can I remove objects with duplicate 'file_url' from a JSON file? { "0": { "file_url": "apple", "name": "apple.jpg" }, "1": { "file_url": "dog", "name": "dog.jpg" }, "2": { "file_url ...

Oops! Looks like Laravel has hit its limit with 256 nesting levels in the function

I recently encountered a problem while working with an API that provides a mixture of JSON, STDClass, and Arrays. My main focus was extracting specific data from this nested structure which I managed to accomplish. However, the issue arose when I attempted ...

Tips for sending arguments up in Angular2

I need to supply an argument to a function. <select class="chooseWatchlist" (change)="updateWatchlistTable(item.name)"> <option *ngFor="let item of _items">{{ item.name }}</option> </select> It's crucial for me, as I have ...

What is an alternative way to replicate the functionality of jQuery's remove() method using only vanilla JavaScript?

Here is the line of code I have: $('.js-cover-menu-dropdown > li > ul').remove(); This code removes all ul elements from the lis within .js-cover-menu-dropdown. I am curious about how I could rewrite this using plain JavaScript. ...

How does JavaScript function syntax differ in Next.js and JSX?

I'm in the process of creating a function that allows users to select different sizes. It currently works fine with just JavaScript and HTML, but I'm encountering an error when using it in Next.js. Can someone confirm if my syntax for the JavaScr ...

Executing Rake tasks on the live server fails because of an issue with ExecJS

I currently have a Rails 4 application running on a RHEL 6 server. The production environment utilizes Passenger and Apache2. Recently, I've been attempting to schedule Rake tasks in the production environment using the Whenever Gem and Cron. Howev ...

Retrieve the element located within a "block" element that is relative to the user's click event, without the

I'm pondering whether it's feasible, but here's my concept: Within my page, there are multiple identical blocks with the same classes, differing only in content. I am unable or unwilling to assign IDs because these blocks are dynamically g ...

Implementing AJAX requests in jQuery DataTable with ASP.NET MVC

For some time now, I have been using the jQuery DataTables 1.10.13 plugin. Recently, I encountered an issue related to the ajax data source for my HTML table. This is how I initialized jQuery DataTable inside Files.cshtml <script language="javascript" ...

I am struggling to make Angular Charts display labels the way I want them to

Struggling to customize an angular chart for my project. The x axis should display dates and the mouse over should show client names, all retrieved from an array of resource objects in a loop. The loop code snippet is as follows: angular.forEach(charts, ...

Spotfire: Changing a URL in an input field after it has been entered by the user

Currently, I am faced with a challenge related to importing a file in spotfire based on the path provided by the user. To accomplish this, I am utilizing a data function written in R script. In R, it is essential to note that all "\" characters are n ...

What is preventing the listener from activating?

I came across some HTML code that looks like this: <form id="robokassa" action="//test.robokassa.ru/Index.aspx" method="post"> <input type="text" id="OutSum" name="OutSum" value="" placeholder="Сумма пополнения"> ...

Problem with the WP Rocket helper plugin that excludes JS scripts from Delay JS only at specific URLs

Looking for assistance with a helper plugin that excludes scripts from "Delay Javascript Execution"? You can find more information about this plugin here. The specific pages where I want to exclude slick.min.js and jquery.min.js are the home page and tabl ...