Creating a JSON object using an input variable

My goal is to create a JSON object using input variables from two fields. Upon clicking a button, I want to capture the input values and use them to construct a JSON object accordingly. However, I am encountering issues with successfully creating the JSON object with the entered values.

Initially, I attempted the following:

// Fetching the input values as variables
let id=document.querySelector("#id");
let title=document.querySelector("#title");

Firstly, I tried the code snippet below. Unfortunately, it resulted in an empty value rather than the expected string:

var vObj = '{"id":' + id.value + ',"title":' + title.value + '}'

Another approach I experimented with was:

var vObj = {"id":{}, "v_title":{}, "v_category":{}};
vObj.id = id.value;
vObj.title = title.value;

Furthermore, I tested the following code snippet:

let asd = id.value;
let bsd = title.value;

var vObj = {id:asd, title:bsd}

Unfortunately, this also returned an empty value instead of the desired variable value.

Upon further investigation, I discovered that there was a typographical error in the button trigger which may have been causing these issues. My apologies for overlooking this mistake.

Answer №1

To generate valid JSON, start by creating an object with specific properties and then utilize the JSON.stringify method:

//let id = document.querySelector("#id").value;
let id = 'my_id';
//let title = document.querySelector("#title").value;
let title = 'my_title';
console.log('ID: ' + id);
console.log('Title: ' + title);

var vObj = { id: id, title: title };
var json = JSON.stringify(vObj);
console.log(json);

The following line of code:

var vObj = { id: id, title: title };

Defines an object with an id property that holds the value of the id variable, along with a title property holding the value of the title variable.

This line of code:

var json = JSON.stringify(vObj);

Converts the object vObj into a JSON string.

Output:

ID: my_id
Title: my_title
{"id":"my_id","title":"my_title"}

Further clarification based on @FelixKling's feedback

In ES6, you can simplify the declaration of the vObj object using:

var vObj = {id, title};

This will create the same object but assumes properties named id and title. If your variables have different names, this shorthand will not apply.

Answer №2

To begin, start by creating a new object and then converting it to a JSON string.

var json = JSON.stringify({ "id": id, "title": title });

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 input field automatically populates with the username that has been stored in the browser's form

Issue: I have created an input field with the type text, but upon page load, it gets automatically filled with a username saved in the browser's form data for this website's login page. I want it to show up clean when the page loads. <input t ...

When an Android app is closed and then reopened, the JSON stored list containing objects reverts back to the superclass

Currently, I am managing an ArrayList <GeneralTemplate> items Throughout the execution of my program, I keep adding Routines as subclasses of GeneralTemplate. For instance, items.add(new Routine("Test"));, which functions smoothly. An essential asp ...

Issue with switch statements in PHP/JavaScript causing unexpected 'undefined' behavior

Exploring a switch statement: var currency = ""; switch (row.currency) { case 1 : currency = "&pound;"; break; case 2 : currency = " &#36;"; break; case 3 : currency = "&euro;"; break; default: currency = "&po ...

The incorrect ordering of my array within a nested ng-repeat in AngularJS

I have extracted Json data from a mongodb database collection. Successfully displayed the keys of this json. Currently attempting to present an array in a table using a double ng-repeat in my view. Although I am close to achieving my desired outcome, th ...

Retrieve information from a template and pass it to a Vue component instance

Being a newcomer to vue, I have a fundamental question. In my template, I have a value coming from a parsed object prop like this: <h1>{{myval.theme}}</h1> The above code displays the value in the browser. However, I want to store this value i ...

When using the command `nodejs fs.rm(path, { recursive: true, force: true })`, an error is thrown stating "ENOTEMPTY: directory not empty"

import { existsSync } from "fs"; import fs from "fs/promises"; export async function createDirectory(path: string) { if (existsSync(path)) { try { await fs.rm(path, { recursive: true, force: true }); } catch (e) { console.log("ERR ...

Customizing individual textareas in tinyMCE can easily be done by adjusting the

This resource provides instructions on customizing features like the menubar and status bar for all form fields within tinyMCE: tinymce.init({ selector: "textarea", menubar:false, statusbar: false, .. }); I am wondering how to achieve th ...

Generated Form Data Automatically

Seeking advice on achieving a specific functionality in ASP.NET Web Form that is similar to the AutocompleteExtender, but requires more flexibility. Here is what I aim to accomplish: There are 2 TextBox fields on the form: CompanyName and CompanyRef (a u ...

Using ReactJS and Redux to dispatch notifications

I have a query regarding displaying notifications for successful or failed user registration actions. Utilizing Redux, I've implemented the following action page: export function registerUserFail(error){ return { type:REGISTER_USER_FAIL, ...

I'm currently in the process of converting this React class component into a Functional Component

I am inclined to stick with functional components because that's what I'm used to. My codebase is primarily built using functional components and I would like to maintain consistency. I haven't really delved into class components yet, as I&a ...

Creating a personalized Material UI theme for enhancing the appearance of a Next.js App Router

Recently transitioned from C# development to diving into Next.js for a client project. Utilizing MUI, I have put in a day of work so far, resulting in a relatively small project. While I grasp the concept of SSR (Server-Side Rendering) theoretically, the ...

"TypeScript function returning a boolean value upon completion of a resolved promise

When working on a promise that returns a boolean in TypeScript, I encountered an error message that says: A 'get' accessor must return a value. The code snippet causing the issue is as follows: get tokenValid(): boolean { // Check if curre ...

Developing a Progress Bar for Uploading Files using ASP.NET and JavaScript

Does anyone have suggestions on how to implement a simple file upload progress feature? I'm looking for something that will display the percentage of the file uploaded. I've come across some complicated codes and plugins, but I just want to sta ...

Error encountered in React Native packager due to naming conflict between "lodash" and "yeoman-generator" libraries

Issue Description Within my current project, I am utilizing "react-native": "0.36.0" along with the following dependencies: "lodash": "^4.15.0" "yeoman-generator": "^0.24.1" Upon using versions above "^3.10.1" for "lodash" and "0.21.2" for "yeoman-gene ...

Is there a way to retrieve the original value of the substr value?

I successfully retrieved the correct value using the substr() method, but I am facing difficulty in getting back the original value. Can someone please guide me on how to achieve this? For example: "AAAAAA" -> AA... but I am unable to revert from AA.. ...

What is the most efficient way to query through a Firestore database containing 5,000 users?

We are currently facing a challenge with our staffing application, which is built using vuejs and a firestore database containing over 5,000 users. Our primary issue lies in the need for a more efficient layout that allows admins to search for users within ...

How can I create a more spacious and stylish JTextField for my address bar?

I am working on developing my Java skills by creating a custom browser. Is there a way to adjust the size and shape of the address bar, which is currently implemented as a JTextField with Swing's default settings? Here is the code snippet I am using: ...

What is the best way to dynamically change the color of my component depending on the prop passed to it?

I am facing an issue with the color of my component changing based on the value of the prop 'level'. Despite using states to set the backgroundColor, all components end up having the same color due to the state being altered for every comment. I ...

React: Implement event handler to filter and display specific items from an array on click

In my setup, I have an array of projects represented as objects which include their names and the technologies used (stored in another array). My current objective is to filter these projects based on which button a user clicks. For instance, if the user s ...

Processing JSON data returned from a PHP cURL request

After making a curl request, I am displaying the response in the following manner. $output = curl_exec($ch); $json = json_decode($output, true); echo $output; echo $json; Here is the resulting output. HTTP/1.1 201 Created Server: nginx/1.15.8 Date: Wed, 0 ...