Converting an object to JSON in javascript: A step-by-step guide

I have been attempting to convert my object person into a JSON format.

const person = new Object();
    person.firstName = 'testFirstName';
    person.lastName = 'testLastName';

var myJson = JSON.stringify(person);
                        
console.log(myJson);
console.log(typeof myJson); // Despite calling it JSON, the return type is actually string.

When I attempt to display my supposed JSON and check the type of the element (myJson), it shows as an string.

Can anyone provide assistance in understanding this discrepancy and suggest a better approach to achieve my goal?

Answer №1

Understanding the distinctions between JSON and JS objects is crucial. This information can be found in the following answer: link.

Typically, when you retrieve a JSON file, it is in string format. In order to utilize it as an object, you need to parse the JSON file so that the string gets transformed into an object.
In your script, utilizing JSON.stringify(person) has already converted the object into a JSON file.

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

Having trouble sending an ajax request from localhost to a remote server

When attempting to make an ajax request (using jquery) from my local server to a remote page where I am the administrator, I encounter the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

Using Powershell to Retrieve an Object from a JSON File

I'm currently working with a JSON file in Powershell and I need help structuring it properly. Here is the format of the file. [ ["device1", ["software1", versionA]], ["device2", ["software2", versionB]], ["device3", ["software3", "version ...

Using Typescript to pass a property as one of the keys in an object's list of values

In my React Native project, I need to pass a string value from one component to another. The different options for the value can be found in the ScannerAction object: export const ScannerAction = { move: 'move', inventory: 'inventory&apo ...

Step-by-step guide for building and populating a JavaScript Dictionary

Does anyone know how to create a Dictionary with a key and a list of values pair in Python? I have been able to create dictionaries with a single value for each key, but now I need to store multiple items as values for each key. Here is what I have tried: ...

What is the most effective way to compare a nested array using the map or filter function in order to return only the first match

Here is a code snippet showcasing the data object containing information for the codeworks array with code and text values. There is a key array named code = ["ABC","MDH"] and the expected output is displayed in the following code snippets. const data = ...

Data binding functions properly only when utilizing the syntax within the select ng-options

In the book AngularJS in Action, I came across this Angular controller: angular.module('Angello.Storyboard') .controller('StoryboardCtrl', function() { var storyboard = this; storyboard.currentStory = null; ...

Modify the background color of a pseudo-element's property value dynamically

How do I change the background color of my burger menu by clicking on an icon? This is the CSS code I have: :root{ --pseudo-backgroundcolor: yellow; } .menu__icon span, .menu__icon::before, .menu__icon::after{ background: va ...

The Wikipedia API is unable to be loaded using the XMLHttpRequest

I have encountered this error before on this platform, and although I managed to fix it, I am seeking a more in-depth explanation of the solution. For a project where I am learning, I decided to create a Wikipedia Viewer application. The first step was to ...

The Discord.js error message popped up, stating that it was unable to access the property 'then' since it was undefined

I'm currently working on implementing a mute command for my discord bot, but I'm encountering an error that says; TypeError: Cannot read property 'then' of undefined I am unsure of what is causing this issue and would greatly apprecia ...

What is the best way to display information in a newly added row of a datatables table?

Working on ASP.NET gridview conversions with datatables.net plug-in. The reason behind this is complex and subject to debate. But, I need assistance with a specific issue. The process of converting the gridview using Javascript was simple and effective. H ...

Encountering a JSONDecodeError when sending a python dictionary via AJAX post

I have encountered an issue when passing a Python dictionary to a template and then using $.post to send it to a Django view. When I attempt to json.loads it in the view, I am getting a JSONDecodeError. Does anyone know how I can resolve this? //1. vars t ...

When utilizing ASP.NET Core Razor pages for file uploads and utilizing AJAX Post to send the file to an IFormFile handler, the request

I have a straightforward task that involves uploading a file and using AJAX to post it to the Index page: <input type="file" id="file-selector" accept=".txt"> Here is the corresponding Javascript: const fileSelector ...

Pause the execution of an AJAX callback function after numerous AJAX requests

I have two separate Ajax calls in my code. Both of them have different callbacks that need to execute upon successful call. $.ajax({ type: 'POST', url: "url1", success: foo1 }); $.ajax({ type: 'POST', url: "url2", ...

Ways to alter the color of an icon when hovering over it

Is there a way to change the color of a material icon inside an IconButton material component when hovering over the IconButton? I've tried adding a class directly to the icon, but it only works when hovering over the icon itself and not the IconButto ...

When attempting to declare a functional component in React utilizing styled-components in TypeScript, an error is encountered stating "No overload matches this call."

Playground https://codesandbox.io/s/typescript-type-checking-question-0b42t Sample Code type BadgeTypes = { success: string; secondary: string; alert: string; text: string; }; type Theme = { fonts?: object; borderRadius: string; primary?: o ...

Complete a bootstrap row and begin a new row after every nth div element

I have a grid layout in Bootstrap that I will be filling with blog post thumbnails. <section class="container"> <div class="row thumbs"> <div class="col-sm-3">content</div> <div class="col-sm-3">content</div> ...

Unraveling JSON stored in MySQL

I have stored a JSON string in my MySQL database with the following structure: { "string1": { "substring1": 1234 }, "string2": { "substring2": "substring2.1", "substring3": "substring3.1", "substring4": { ...

Expecting a declaration statement for exporting React

When attempting to export my component, I encounter an error in my editor stating export declaration statement expected Here is the code snippet: export Header from './Header/Header'; However, if I modify it like this: export {default as Head ...

Is there a way to attach a model to an Angular directive?

Currently, I am implementing angular's typeahead functionality using the following resource: I have created a directive with the following template: <div> <input type="text" ng-model="user.selected" placeholder="Ty ...

Tips for extracting tables from a document using Node.js

When converting an XML document to JSON using the xml-js library, one of the attributes includes HTML markup. After parsing, I end up with JSON that contains HTML within the "description":"_text": field. { "name": { ...