What is the process of extracting data from a variable and inserting it into a JSON object in JavaScript?

I have just started learning about JSON and am currently working on a JavaScript program. I've been searching for a straightforward solution, but I may not be framing my question correctly.

My goal is to allow users to input their information which will then be added to a JSON object. However, I'm struggling to get JSON to accept the value. Let's say we have userName="Bob".

const userJSON=`{
    "playerName": userName
}`;

I want userJSON to result in "playerName": "Bob". But unfortunately, I keep getting an error stating that userName is not valid JSON.

Is there a simpler way to achieve this? I can successfully parse information if it appears as "playerName":"Bob", but since this is intended for a game where users can add their own usernames, I need it to be more dynamic.

Answer №1

When working with template strings, make sure to include the variable using ${} along with quotation marks around string variables, as shown below:

const userData = `{ "name": "${user}" }`; 

Alternatively, you can create the object first and then stringify it (which is a more sensible approach):

const userObject = { "name": user }; 
const userData = JSON.stringify(userObject);

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

What could be causing this JavaScript code to run sluggishly in Internet Explorer despite its simple task of modifying a select list?

I am currently developing a multi-select list feature where users can select items and then rearrange them within the list by clicking either an "Up" or "Down" button. Below is a basic example I have created: <html> <head> <tit ...

Using Angular.js to fetch information from a MySQL database

I'm currently trying to retrieve data from a MySQL database in an Angular.js application. I have gone through multiple tutorials, but unfortunately, none of them have been successful for me. I have a PHP script that returns a JSON array with example ...

The process of filtering JSON data in Angular can be easily achieved by utilizing the filter functionality

Seeking recommendations for useful books or online resources to learn how to filter JSON data effectively using angular filters. Interested in tackling more complex datasets. Any assistance on this matter would be greatly appreciated. ...

Upload multiple files at once, edit span text, and retitle to files chosen

I need help updating the span text for each file uploader on my page. I want the default "Choose a file..." text to change to the selected filename. Can someone assist me with this? Here is a Js fiddle that I've been working on. This is my HTML mark ...

What is the best way to find the difference between two time moments using Moment

Hello everyone, I could really use some assistance with Moment.js. I have two input fields, one labeled Start and the other labeled Stop. start = moment().format('LT'); // This works when I click on the play button stop = moment().format(' ...

When you try to remove an element from an array by its index in Vue JS, the outcome may not be

Here is an array that I have: var hdr = ("name", "date", "start_time", "selling_item", "total_call", "end_time", "ad_num", "area", "order_num"); //this data comes from the database Now, I need to rename these array elements according to prope ...

Converting text data into JSON format using JavaScript

When working with my application, I am loading text data from a text file: The contents of this txt file are as follows: console.log(myData): ### Comment 1 ## Comment two dataone=1 datatwo=2 ## Comment N dataThree=3 I am looking to convert this data to ...

Document: include checksum in HTML

I have a set of three files. The file named loader.js is responsible for creating an iframe that loads another file called content.html, which in turn loads content.js. I have made loader.js publicly available so that other users can include it on their ow ...

Buttons aligned vertically alongside an input text field

I am trying to align two buttons vertically under an input text box with the middle aligned. This is what I have done so far: jQuery(document).ready(function($) { // Implementing bootstrap minus and plus plugin // Reference: http://jsfiddle.net/lael ...

Attempting to cycle through a collection of dictionary elements

I have a JSON list containing ServerIPList with PrivateIP values that I want to iterate through and append to the empty InstanceIds list: Here's the code snippet: InstanceId = [] message = [{"SNowTicket":"RITM00001","ServerIP ...

Transform JSON data into key-value pairs using Python

I am currently working with a JSON file that has the following structure: {"Africa": { "invitee_event_type_page": { "Total Events": "194" }, "invitee_meeting_cance ...

Tips for retrieving numerical values from JSON paths using Scala

I just received the following response: { "code" : 201, "message" : "Your Quote Id is 353541551" } To extract the number 353541551 from the above response, I attempted to use some basic Scala code snippets. Here's what I tried: .check((status i ...

Can anyone offer any suggestions for this issue with Angular? I've tried following a Mosh tutorial but it's

Just finished watching a video at around 1 hour and 35 minutes mark where they added the courses part. However, I encountered an error during compilation. ../src/app/app.component.html:2:1 - error NG8001: 'courses' is not recognized as an elemen ...

Determining the height of a Bootstrap column in relation to another element

Utilizing the grid layout from bootstrap, I have the following structure: <div id="prof_cont_enclose"> <div class="row"> <div class="prof_cont_row"> <div class="col-xs-12 col-sm-4 col-md-2 col-lg-2 prof_elem"&g ...

Issue with formatting and hexadecimal encoding in JavaScript

I am currently developing a LoRaWAN encoder using JavaScript. The data field received looks like this: {“header”: 6,“sunrise”: -30,“sunset”: 30,“lat”: 65.500226,“long”: 24.833547} My task is to encode this data into a hex message. Bel ...

Organizing a Collection of Likes within an AngularJS Service

I have a like button on my profile page that, when clicked, should add the user's like to an array and store it in the database. Within my profile controller, I have the following code: $scope.likeProfile = UserService.likeProfile(loggedInUser,$stat ...

Downloading a PDF file received from a Django view using JavaScript and jQuery

I have a celery task that creates PDF files on the click of a button. When the button is clicked, the JavaScript side will keep checking until the task is done, and when it is, it will download the file. Some recursion should do the trick: $(".getPdf").o ...

What is the process of changing a number to the double data type in JavaScript or TypeScript?

Within a single input field, users can enter various numbers such as 12, 12.1, 12.30, and 12.34. The challenge is to pass this value in a service call where only the value can be sent as a number but with two decimal points. let a = input //a will be a ty ...

Nightwatch failing to locate element within iFrame

I'm currently facing a challenge when trying to access an element within an iframe. Despite successfully switching to the frame, Nightwatch keeps returning "element not found" whenever I attempt to verify its presence or visibility. Below is a snippe ...

Completing a form and saving data to a document

I have a form that successfully writes to a text file using PHP. However, after submitting the form, the page reloads and shows a blank page. Currently, there is a message that appears using jQuery after the form is submitted. My goal is to prevent the pa ...