Simple guide on converting a JavaScript object into JSON

I am currently facing a challenge in converting the following JavaScript object into valid JSON format:

[{ 
 '"Sno"': '"1"',
 '"Purchase Date Time"': '"2017-11-14 14:09:32"',
 '"Txn Type"': '"COD"',
 '"Order Status"': '"DELIVERED"'
},
 { 
 '"Sno"': '"2"',
 '"Purchase Date Time"': '"2017-11-14 14:09:32"',
 '"Txn Type"': '"COD"',
 '"Order Status"': '"DELIVERED"'
}]

Despite trying to use JSON.stringify(), the output produced is not satisfactory:

"[{"\"Sno\"":"\"1\"","\"Purchase Date Time\"":"\"2017-11-10 14:09:32\"","\"Txn Type\"":"\"COD\"","\"Order Status\"":"\"DELIVERED\"",}]"

This current representation hinders my ability to access individual elements effectively. What I really need is the ability to retrieve values like objectName[i].Sno.

What steps can I take to achieve this desired outcome?

Answer №1

If you're still keen, follow these steps:

var js = [{ 
 '"ID"': '"101"',
 '"Name"': '"John Doe"',
 '"Age"': '"25"'
},
 { 
 '"ID"': '"102"',
 '"Name"': '"Jane Smith"',
 '"Age"': '"30"'
}];

var json = JSON.parse(JSON.stringify(js).replace(/\\\"/g, ""));

console.log(json[0]["Name"]);

Firstly, convert to a string, eliminate all \" pairs, and then change it back to JSON format.

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

When attempting to log API results in Next.js, a TypeError occurs because the property is undefined

I'm encountering a rather unusual error. In my Next.js app, I am attempting to console log the results of an API call to see what data I receive. The API function is responsible for verifying if a user is logged in, and if they are, I render a specifi ...

Exploring the retrieval and iteration of JSON data in Flutter

As a beginner in Flutter, I decided to follow a tutorial on building a news app. I created a class for fetching data and everything seemed fine until I encountered an error while executing the app. Can someone please help me understand what is wrong with t ...

Newbie in Distress: Help Required Due to Server Error

Currently working on the contacts page for a website and I need the div element to disappear once an email is successfully sent. In order to hide a Div element using Javascript, I created the following function: function hideDiv(){ document.getElement ...

What is the best way to insert text into a span element within a for loop using JavaScript?

I am currently working on form validation using an array and a loop. In each required field, I have created empty span elements. Here is the JavaScript code that I have set up: var name = document.querySelector('#Name').value, firstLastName = ...

Encountering an Error during the Installation of MapBox SDK in React Native

After creating a React Native project with Expo using expo init MapTry, I encountered an issue while trying to install the MapBox library. Despite following the installation guide at https://github.com/rnmapbox/maps#Installation, I faced an error message w ...

Is the condition failing to evaluate for all td elements?

I am currently dealing with an HTML table. When I select a checkbox, I aim to compare the values of the cells in each row. This comparison works correctly for the first row, but it does not work for any subsequent rows. HTML Code - <form role="fo ...

Issues with MySQL not functioning properly when using Promise.All in a Node.js environment

When it comes to running multiple mysql queries asynchronously in express node.js, MySQL works well with simple callbacks. However, I wanted to take it a step further by using async await with promise.all. I also experimented with promise.allSettled, but u ...

Listening for events on an array of elements using jQuery

My task involves populating an array with elements using the .each() method and the $(this) selector. (function($){ var elements = new Array(); var index = 0; $("img").each(function() { if($(this).attr("attribute")){ $(thi ...

avoidable constructor in a react component

When it comes to specifying initial state in a class, I've noticed different approaches being used by people. class App extends React.Component { constructor() { super(); this.state = { user: [] } } render() { return <p>Hi</p> ...

What steps should be taken to verify email validation? Is there an error we need to address

I attempted to implement this straightforward example. final String email = edt.getText().toString().trim(); final String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; btnchk.setOnClickListener(new OnClickListener() { @Ov ...

Generating a new array based on the keys found in a collection of objects

My array structure is quite complex with multiple objects containing different properties. let arr = [ { id: 1, name: "tony", hatColor: "blue" }, { id: 2, name: "larry", hatColor: "red" }, { id: 3, name ...

Assign an AJAX call to retrieve data from a MySQL table and store it in a

In my database, I have a table that includes fields for 'user_name' and 'user_round'. My goal is to set the 'user_round' field to match the value of a JavaScript variable called 'Level'. However, when I run my code, ...

The active class in the Vue.js component navigation only takes effect after the second click

Within a menu component placed inside a view accessed through its own route (/how-it-works), I am facing an issue with the header component structure, outlined below: <nav class="nav"> <ul class="top-menu"> <li v-for="menu in me ...

Inheriting from the AudioWorkletProcessor class and incorporating a pre-existing audioNode within the class

My goal is to extend the AudioWorkletProcessor class in order to create a new AudioNode. However, I want to include an existing audioNode, such as a GainNode, within the class - specifically inside the process function. The challenge lies in accessing the ...

What is the process of memory allocation for variables in Javascript?

Can you explain to me how local variables are allocated memory in JavaScript? In languages like C and C++, local variables are typically stored on the stack. Is this also the case with JavaScript, or are all variables stored in the heap? ...

Ways to retrieve an array following a function call

After a lot of testing and troubleshooting, I finally got my array to function properly in the console. However, when I click the button, the array is displayed on the console but not in my HTML. TS: jogar(){ for(var u=0;u<6;u++){ this.y ...

creating dynamic applications using ant framework

I'm having some challenges while trying to develop JS applications with Ant. I have a directory named src and each subdirectory inside it is considered a "mini-app". When I iterate through each subdirectory using subant, I'm struggling to get ...

Express: Every declaration of 'user' must have the same modifiers

In my application, I am utilizing both express and passport. Within these packages, there is a user attribute within the Request interface. Currently, the express package has a user attribute in the request object, such as req.user, but no additional prope ...

In what way can the jQuery .each() function make use of the index as a variable?

Consider the jQuery .each() function, which comes with a useful feature. For example: $('.element').each(function(index){ console.log(index); }); Here, you can access the index of the currently selected element using the "index" variable. ...

Is there a way to verify the existence of an element based on its class name?

In the title of my question, I mentioned that my element lacks an id attribute. So how can I determine if it exists or not? Here is the HTML code: <div class="classname">something</div> Note1: If there was an id attribute like this: var el ...