Inserting a variable into a JSON string

Within my code, I have a basic variable containing strings that are converted into a JSON object. My goal is to create an input field where a person's name can be entered and added to the text.

The current setup looks like this

var text = '{"students":[' +
'{"firstName": "Brendan","lastName":"Skousen" },' +
'{"firstName":"Scooby","lastName":"Doo" },' +
'{"firstName":"Your","lastName":"Mom" }]}';

Additionally, I have a variable for the input value

var first = document.getElementById('first').value;

My desired outcome is for the 'text' variable to function as follows:

var text = '{"students":[' +
'{"firstName": first,"lastName":"Skousen" },' +
'{"firstName": first,"lastName":"Norman" },' +
'{"firstName": first,"lastName":"Coatney" }]}';

You can view the complete code example at: http://codepen.io/bskousen/pen/xbPLew

Answer №1

var data = '{"students":[' +
'{"firstName": ' + escape(first) + ',"lastName":"Skousen" },' +
'{"firstName": ' + escape(first) + ',"lastName":"Norman" },' +
'{"firstName": ' + escape(first) + ',"lastName":"Coatney" }]}';

Utilizing the escape function as shown here.

Answer №2

If you want to achieve the same functionality as demonstrated in your example, using a template engine is advisable. By incorporating extra characters around the variable based on the chosen engine, you can make it work seamlessly. In this scenario, concatenation seems like the simplest approach.

var text = '{"students":[' +
'{"firstName": ' + first + ',"lastName":"Skousen" },' +
'{"firstName": ' + first + ',"lastName":"Norman" },' +
'{"firstName": ' + first + ',"lastName":"Coatney" }]}';

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

Make sure to incorporate certain node_modules folders within Babel 7

My issue involves a dependency located in the node_modules directory that requires compilation through Babel. Despite upgrading my stack, I am unable to get Babel to compile the dependency. Current versions: @babel/core 7.5.4 webpack 2.7.0 Here is my w ...

How can jq be used to compactly format specific fields?

Is jq the optimal solution for formatting arbitrary JSON? cat my.json | jq . is effective for pretty-printing JSON, but it can expand each field on separate lines. However, what if certain fields are repetitive, like a list of points? How can we format m ...

Utilizing the Current URL from the address bar as a variable to link within the same page

My goal is to: Extract the current URL address from the browser bar, which will have a format like this: http://example.com/test/index.html?&dv1=1023faf2ee37cbbfa441eca0e1a36c Retrieve the lengthy ID number located at the end of the URL 1023faf2ee37c ...

Sending various FormData instances to Node Express

I am facing a challenge where I need to submit three forms with just one click. The data collected from these forms should then create three separate rows in the database through an API, triggering a POST request. How can I effectively pass all this data ( ...

I am experiencing difficulty with the Click() operation in Selenium web driver as it is not successfully redirecting me to another page

Hello everyone, I could really use your assistance with a problem I'm facing. WebElement wb=driver.findElement(By.name("NavHeader1$tabs$ctl00$btnNavHeaderTab")); Actions act=new Actions(driver); act.moveToElement(wb).perform(); ...

What is the best way to retrieve access to my container/store from this main file?

As a beginner in React/Redux, I am facing an issue where everything works fine in Redux when testing it. However, I am struggling to integrate it into my actual application. I believe that I need to use connect(), but I am unsure of how or where to imple ...

Is there a way to display an image in a React Native app using data from a JSON file?

I am currently working with JSON content that includes the path of an image. I need to display this image in my React Native application. What is the best way to render this image? {"aImages":[{"obra_path":"http:\/\/uploa ...

Display an array containing date objects in a dropdown menu for users to select from

I am working with an API call that returns an array of objects. Each object in the array contains a date or timestamp in ISO format. Right after my render() method, I have the following code snippet: const pickerItems = this.props.currentData.trips.map(t ...

Angular 4: Triggering a function by clicking a link with specific parameters

I am relatively new to working with Angular 4. I have an anchor tag that, when clicked, should redirect me to a link where I also need to pass parameters. I'm unsure if my current approach is correct or not. Above all, I really need guidance on how to ...

What is the best method for ensuring a user remains logged in even after their access token expires, requiring them to log in again to resume their normal

Currently utilizing the Nuxt-axios module alongside a proxy. Implemented common error handling code in Plugins/axios.js export default function({ $axios, __isRetryRequest, store, app, redirect , payload , next}) { $axios.onRequest(config => { i ...

eBay API request error: "You do not have the necessary permissions to complete the request."

While working on integrating the eBay API, I encountered an issue with creating a payment policy. Following the instructions provided in this guide , I generated a token and sent it using Postman. However, I received an error: { "errors": [ ...

The protected routes within a React JS application consistently result in an undefined value

In my ProtectedRoute component for my react application, I am facing an issue with user authentication. I am using react-router-dom v6 to access the token from localStorage, but no matter what, the user variable always returns undefined. import { Outlet, N ...

Including a Pinterest image hover widget following the completion of an Ajax load

I have implemented the Pinterest image hover widget on my website to allow users to easily pin images to their Pinterest accounts. You can find the widget here. (Make sure to click the image hover radio button under button type to see the one I am using.) ...

implementing toggle functionality for an array of items in ReactJS

I have an array and I am trying to create a show/hide feature for each item based on toggling. When I click on one item, it should expand while simultaneously hiding the previously expanded item. Here is the code snippet I have been working on: class App e ...

Countdown timer feature and auto-submit function for your website's page

Currently, I am working on an online exam project that requires the page to be automatically submitted after 10 minutes, regardless of whether the user clicks on the submit button or not. Additionally, I want to include a countdown timer to display the r ...

A step-by-step guide to simultaneously updating various Google Sheets through gspread

I am facing a challenge in updating multiple Google sheets with Python, and so far, none of my attempts have been successful. My goal is to input data once and automatically have it copied to another spreadsheet. Below is the code I have been working on: ...

The $resource.query function will now return an array of characters instead of a single string when splitting strings

Recently, I've been working on utilizing an Angular $resource in my project. Here's a snippet of the code: angular.module('app') .factory('data', function ($resource) { var Con = $resource('/api/data', {}, { ...

What is the reason for the jQuery plugin not being applied after replacing the page content with an Ajax response?

At the moment, I am utilizing jQuery ajax to dynamically add content to my website. Additionally, I have incorporated the jquery.selectbox-0.6.1.js plugin to enhance the style of select boxes on the page. The plugin successfully styles the select boxes up ...

Struggling to concentrate using jQuery?

When the search icon is clicked, I want the focus to be on the input so the user can start typing right away without having to manually click on it. Although I tried using focus(), it doesn't seem to work for this particular input. $('.header__ic ...

modify the b-form-checkbox component in a Vue application

I have inserted the <b-form-checkbox> element into a <b-table>: https://jsfiddle.net/fmattioni/L269rd7s/ This is my current objective: 1 - Initially, all checkboxes in the table are checked using checked="true". 2 - Try unchecking ...