Enforcing quoted keys in a Javascript object

There's often confusion around the difference between

obj = {"foo" : "bar"} 

and

obj = {foo: "bar"}

The explanation is that using quotes follows proper JSON syntax, while no-quotes is just Javascript syntactic sugar. Now, my query is how to convert any unquoted or semi-quoted JavaScript object like:

semi = { "foo" : "bar", hello: "world"}

to a fully quoted object like:

fully = { "foo" : "bar", "hello": "world" }

using JavaScript. I'm not looking for JSON.stringify() as it would return a string; I need a regular JS object. Appreciate your help!

Answer №1

When the Javascript interpreter displays properties, it will quote them if they have special characters such as dashes or spaces.

It's important to note that Javascript objects and JSON are not interchangeable. While they may appear similar, JSON is a string representation of a javascript object, whereas a javascript object consists of actual properties with defined property names. This distinction allows access to these properties using dot syntax, like in the example below:

console.log( semi.foo );

The quotes seen in the string representation are purely for visual purposes and do not reflect how the properties are stored internally.

Answer №2

In JavaScript, object keys are not enclosed in quotes; they are basic string values.

When defining a key in the source code like this:

{ unquotedKey:  "some value" }

it creates an object with a key-value pair. However, the key must follow the rules of JavaScript identifiers.

On the other hand, when defining a key like this:

{ "quoted value!": "some value" }

it does not adhere to the identifier rules.

The same rule applies when accessing property names using dot notation: foo.bar works, but foo["was here"] requires array lookup notation because was here is not an identifier.

Now let's talk about JSON.stringify. This method always quotes property names for exchanging object representations across systems and languages. It's important to note that just because JSON.stringify uses quotes, it doesn't mean quoted keys are superior or the correct way to define object literals in JavaScript.

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

Please identify the path of chromedriver for selenium-standalone

I've encountered an issue when trying to initialize the selenium-standalone server (https://www.npmjs.com/package/selenium-standalone). The error message I receive is as follows: 14:19:09 /usr/local/lib/node_modules/selenium-standalone/bin/selenium-s ...

AngularJS service using $http.get is failing to transfer data to a controller

Just getting started with AngularJS and I'm running into some challenges with the basics. I've been working on a service that uses $http.get to load a couple of Json files. However, when I try to use the service in my controller, I end up with e ...

What makes jQuery objects inherently one-of-a-kind?

After researching jQuery objects on this website, it was mentioned that each jQuery object is distinct, even when created with the same selector or containing references to the exact same DOM elements. For instance, the comparison below would result in fa ...

What is the process by which Elastic Beanstalk executes Node.js application code?

While my application runs smoothly on localhost, encountering no issues, deploying it to other platforms such as AWS or MCS presents a challenge. Specifically, the problem lies in recognizing the file paths required by the consign library to load the route ...

Vue CLI configured with Webpack is experiencing malfunctions following a recent update to dependencies

I'm sharing my package.json details below: { "name": "x", "version": "1.0.0", "main": "index.js", "license": "MIT", "scripts": { "dev": "webpa ...

What could be causing the Google API to malfunction in my Universal Windows App?

Error: 0x800a138f - JavaScript runtime error: Unable to access 'setApiKey' property of undefined or null reference Hello, I am struggling to make this work on my Universal Windows App. There is a sample for Google's URL shortener with instr ...

Incorporating a Link into a Radio Button component in Material-UI using react-router

Greetings! I have two radio buttons and would like to include a link. I attempted to achieve this in the following manner: <RadioButton value="/searchByArtistAndName" label="Artist and Name" style={styles.radioButton} contai ...

The function mysql_query() in PHP is unable to execute the requested SQL query

Here is the SQL query I have been working with: UPDATE approved_student SET barcode='11', phone='11', table_name='2', remark='' WHERE studentid='5230010'; UPDATE approved_student SET barcode='22&apos ...

The data type of Subscription: prototype, NOT ASSIGNED

I am encountering the following error when attempting to return a subscription object. Error Message:-------- Type 'Subscription' does not have the prototype and EMPTY properties that are expected from type 'typeof Subscription' Here ...

Error: 'socket' is inaccessible before it has been initialized, specifically in the context of electron

Trying to configure an electron app where a message is sent to the server, and the server places the value on the read-only textarea. However, upon starting the app, the following error appears in the devtools console: Uncaught ReferenceError: Cannot acc ...

What is the best way to adjust the width of these elements for a perfect fit?

I'm currently working on a website where I have arranged squares in a grid layout. My goal is to make these squares perfect, with equal width and height. The only issue I'm encountering is that they tend to change between fitting two and three sq ...

Matching numbers that begin with zero or are completely optional using Regex

Attempting to come up with a regex pattern that will allow the entry of the specified input into an HTML input field: The input must begin with 0 The input can be left empty and characters may be deleted by the user ^[^1-9]{0,1}[0-9\\s-\& ...

Can I upload a JSON file to a server?

I'm looking to store some basic user data to a JSON file on my external server for use with PHP. While I found a helpful article on how to create a JSON file locally in C# at How to write a Json file in C#?, I'm struggling with saving it to my se ...

Exploring the Versatility of Jsons with Retrofit and Kotlin

My API is delivering a polyphonic Json where the variable addon_item can be either a String or an Array. I have been struggling for days to create a CustomDezerializer for it, but so far, I haven't had any luck. Below is the Json response: ({ "c ...

Creating a FadeIn animation for a hidden div element by using the display:none property

Struggling to implement a fadeIn function for a div tag with a display:none property. How can I make the div tag visible and smoothly fade in while still keeping the display:none property? Attempted solution so far: <div class="graphs_line_based cle ...

Converting a JSON string into a C# object - Transforming an array into a JSON

I am working with a JSON string in C# that looks like this : { "Id": "617723", "Acronym": "", "FirstName": "XXXXX", "LastName": "XXXXX", "Groupe": { "Code": "XXXXX", "Traductions": { "French": "", ...

Sending a POST request with authentication using the Apache asynchronous HTTP client

I've been experimenting with making an asynchronous HTTP request to a web service. Although it seems to work, I'm not entirely confident that I am doing it the right way. Is the method I used for making a POST request and handling authentication ...

Generate an array of HTML files from external sources and randomize their placement within multiple div containers

I am currently working on a website that features a grid made up of divs (4x4) which need to have a set of texts shuffled into them every time the page is reloaded. You can see what it looks like here. Within my index.htm file, I have the following struct ...

What could be causing the error that appears when I execute npm run build command?

I am fairly new to this and feeling quite lost. It seems like I have made some mistakes which are causing me trouble now. My main goal is to run the npm run build command for my React.js project so I can deploy it. However, when I try to execute npm run bu ...

Converting a Counter object into a JSON string using Python

I'm a Python newcomer looking for some assistance. I have this counter object : Counter({1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10, 7: 10, 8: 10, 9: 10, 10: 10}) Each key represents a userId with the value being number_of_posts. What I need ...