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

RestTemplate is unable to convert a JSON array into a Java object

Whenever I attempt to retrieve a list of values using RestTemplate, an error occurs. My setup includes Spring 3.0.0. The issue arises from: org.springframework.web.client.RestClientException: Error while extracting response for type [class [Lru.sandwichc ...

Could it be that express-session is not compatible with express 4.13?

I have followed the setup instructions for express-session as outlined in the documentation, but it seems that my cookie is not being created. According to the documentation, simply setting the request.session value should automatically set the cookie. How ...

Tips for accessing the value of an unchecked checkbox in AngularJS

This is a snippet of HTML code: <p> <input type="checkbox" ng-model='add_product.kids' class="filled-in" id="filled-in-box1" /> <label for="filled-in-box1">Kids</label> </p> My goal is to obtain the value "fa ...

Harnessing the Power of JSON in Rails to Enhance Your jQuery UI Autocomplete Form

In the context of a rails application, I have been exploring different methods to fetch data from a JSON file. Despite my efforts, I have not been able to find a solution that suits my requirements. The static data I have is quite extensive, consisting of ...

Black-colored backdrop for Mui modal

Currently working with a mui modal and encountering an issue where the backdrop appears as solid black, despite setting it to be transparent. I attempted to adjust the color to transparent, but the issue persists. ...

A step-by-step guide on leveraging ethereumjs-tx within a web browser

Is it necessary to install npm ethereumjs-tx when utilizing the browser-based version downloaded directly from GitHub? If so, how can we incorporate the ethereumjs-tx module into our script file? It seems like these are two separate components based on ...

Accessing WCF REST endpoint using Ajax and transmitting data in JSON format

I have developed a Rest service in WCF (demo), which provides me with the following output: {"GetEmployeeJSONResult":{"Id":101,"Name":"Sumanth","Salary":5000}} Now, I have created an ASP.NET website where I am utilizing AJAX JSON to call this rest service ...

The process of deserializing JSON data in VB.Net

I have a JSON data that I need to convert back into objects. Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim client As New RestClient(BaseUrl) Dim Respons As Object client.Authenticator = O ...

How can an Angular Component be created in the browser using the standard method?

Attempting to develop a basic Angular example using JS/ESM. It has been some time since working within the angular environment, and there appear to be two primary choices: Utilizing the UMD lib (preferably to be avoided) Using the ESM2015 folder and loadi ...

Placing a user's username within an ejs template using express and node.js

Currently, I am attempting to integrate the username into a layout using ejs templating with node and express. Below are the steps I have taken: Mongodb model: const mongoose = require('mongoose') const Schema = mongoose.Schema; var uniqueValid ...

How can one element be made to rely on the presence of another element?

I'm currently working on my portfolio website and encountering an issue. Whenever I hover over an image of a project, the image expands in size, becomes less transparent, and a description of the project pops up. However, I would like to include a lin ...

Converting HTML Javascript to JAVA with the help of Selenium

Can someone help me extract the value of h1 as a string using selenium? Check out the HTML javascript snippet below- <script type="text/javascript"> $(window).load(function() { var $windowHeight = $(window).height() -12; $(" ...

In JavaScript, the gallery feature with Lightbox effect creates a unique touch as only half of the screen fades to black in

Hello everyone, I'm a complete beginner when it comes to programming so please be gentle with me on my first question :) I'm trying to put together a simple website with a lightbox gallery, and you can check out what I have so far here. The prob ...

Personalized Svelte interface Slider tag

I am trying to customize the label of a smui/slider in a tick marks and discrete slider. While I found instructions on how to do this using material web components at https://github.com/material-components/material-components-web/tree/v13.0.0/packages/mdc- ...

Guide to displaying all files from firebase storage on a screen

I'm struggling to display all the files from my firebase storage. I've tried pushing them into an array, but I can only get one file name. Any ideas on how to push all the files into the fileName array? function Home() { const [fileURL, setFile ...

Sending JSON-encoded data using HTML5 Server-Sent Events (SSE) is a

I have a script that triggers an SSE event to fetch json encoded data from online.php. After some research, I discovered methods for sending JSON data via SSE by adding line breaks. My question is how to send JSON through SSE when the JSON array is genera ...

Enhancing Spring REST for optimal JSON integration with lists and objects

Can Spring support this JSON without creating a new object in Java? Perhaps using a Map? JSON: { "object":"1", "list":[ { "id":"1" } ] } Java: @RequestMapping(method = RequestMethod ...

Angular.js reports that the custom HTTP response header is missing

Despite Chrome showing the correct POST response headers, my custom HTTP header X-Auth-Token is returning null in the callback function for the POST request. Angular.js seems to only be returning Cache-Control and Content-Type, with everything else showing ...

React Native Child Component State Update Issue

In my code, there is a Child component that triggers a function in the Parent component. However, when the function is triggered, an error related to the setState method is thrown. Issue with Promise Rejection (id: 0): The '_this12.setState' i ...

Updating ngModel using the value retrieved from a service call

After experiencing dissatisfaction with Angular's form validation, I decided to develop my own solution. However, I have encountered a perplexing issue that has me at a loss. Here is how my setup looks: I employ a directive to create a new form. Th ...