What is the correct way to have JSON.Stringify properly parse a variable?

I'm struggling with this issue 😞. My Client is performing an ajax httppost and I need to send the following data:

  private doSaveQuery(queryName: string): void {

    const info = {};
    info['userName'] = 'admin';
    info['userQueryName'] = queryName;
    ...

But when it gets stringified, it turns into this:

{"userName":"admin",
 "userQueryName":{"queryName":"MyName"}
}

Why does it take my variable name "queryName" and add it as a key to my value?

How can I achieve this format instead?

{"userName":"admin",
  "userQueryName":"MyName"
}

I believe this is a simple fix, so I appreciate your patience with my ignorance 😅.

Thanks in advance!

Answer â„–1

While encoding the object, it appears that the variable queryName is not a simple string, but rather an object that looks like {queryName: 'MyName'}.

To correct this issue, ensure that queryName is just the string MyName.

info['userQueryName'] = 'MyName'

In other words, queryName may not be the straightforward string you initially thought it was.

Here is an example of your current implementation:

const queryName = {queryName: "MyName"}
const info = {
  userName: "admin",
  userQueryName: queryName
}
console.log(JSON.stringify(info))

To rectify this, update queryName to a simple string:

const queryName = "MyName"
const info = {
  userName: "admin",
  userQueryName: queryName
}
console.log(JSON.stringify(info))

If this is not feasible, an alternative approach is to construct info using the property:

const queryName = {queryName: "MyName"}
const info = {
  userName: "admin",
  userQueryName: queryName.queryName
}
console.log(JSON.stringify(info))

Answer â„–2

When you specify a type as a string in TypeScript, it should typically catch any errors where you're not passing a string. However, sometimes things don't go as expected.

function getMyJSON(queryName) {
   const info = {};
    info['userName'] = 'admin';
    info['userQueryName'] = queryName;
  return info;
}

const a = {queryName:"name"};

console.log(JSON.stringify(getMyJSON(a)));

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

Angular service providing components (TypeScript error)

This is my first time trying to dynamically inject components and so far, I've been successful. However, there's an error in Typescript that's bothering me (I don't like having errors in my code). If you want to check out the app, here ...

What are the steps to create an endless scrolling feature?

I'm trying to create a slider with a horizontal scrolling effect, but I've hit a roadblock. How can I make the slider scroll infinitely? In my code, you can see that after Item 6, it stops scrolling and I have to scroll backward. However, I want ...

What are the steps to start a project on a personal computer?

Utilized on   - Windows 7, 64-bit I am interested in exploring how the project functions with github.com - project. Query: How can I get the project to do this? Steps Taken:   1. Saved the project to the directory. c:\test\visualStudio ...

Troubleshooting Next.js and Tailwind CSS Breakpoints: What's causing the

Having trouble with my custom breakpoints. For instance, I attempted the following: <div className="flex flex-row gap-5 mb-5 md:ml-15 sm:ml-15"> ... </div> The margin is not being applied on small and medium screens. Here are the th ...

The Vue.js v-on:mouseover function is not functioning properly in displaying the menu

When I hover over a LI tag, I want to display a menu. I have successfully implemented it using a simple variable with the following code: @mouseover="hoverFormsControls=true" @mouseleave="hoverFormsControls=false" However, when I attempted to use an arr ...

Leveraging route configuration's scope in HTML

As a beginner in AngularJs, I am currently exploring the creation of a single page application. However, I am encountering difficulties in converting my initial code into more professional and efficient code. During this conversion process, I have separate ...

Is there a way to restrict the amount of user input that is allowed?

Is it possible to restrict the input quantity when using the built-in arrow icon in the text field, but not when typing manually? https://i.sstatic.net/jjogP.png <TextField variant="outlined" label="Quantity" onChan ...

Tips for sending JSON objects to web services using URLs

Is there a way to properly pass JSON objects to web services? I am currently attempting it like this: firstname=jhon&lastname=mic&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ae7ebe3e6b7e0e2e5e4caede7ebe3e6a4e9e5e7" ...

The issue persists where Chrome WebAPI's chrome.webRequest.onBeforeSendHeaders is failing to modify the parameters in the outbound requests

I have been attempting to include an IP address in the X-Forwarded-For parameter within the requestHeader, but my code does not seem to be working based on the examples provided in the Chrome API. Below is the code snippet I am currently using: var reque ...

Interactive Communication: PHP and JQuery Messaging Platform

I am developing a social networking platform and I am looking to integrate a chat feature. Currently, I have a home.php page that displays a list of friends. The friends list is loaded dynamically using jQuery and PHP, like this: function LoadList() { ...

Creating a Custom Class for a Custom Button in TinyMCE 4 Using addButton()

Is there a way to add a custom class to a custom button using the addButton() function in TinyMCE? Here is an example: editor.addButton('keywords', { text: 'Insert Keywords', class: 'MyCoolBtn', ...

Node.js: Steps for receiving an ArrayBuffer in a $http request

I made a request using $http.post from Angular.js to Node.js, expecting to receive an ArrayBuffer. Here is the code snippet: $http.post('/api/scholarships/load/uploaded-files', Global.user, {responseType:'arraybuffer'}).success(functi ...

Encountering a RangeError when transmitting OpenLayers3 event via AJAX

An error is appearing in the chrome console stating: RangeError: Maximum call stack size exceeded The code I am using is as follows: draw.on('drawend', function(evt) { var fe = evt.feature console.log(fe); ...

When the child state changes the parent state, useEffect may not be triggered for the first time

Component for children export const FlightRange = (props) => { const [value, setValue] = useState(props.value); return ( <> <input type='range' min={1000} max={50000} step="500&quo ...

Attempting to use vue-test-utils-getting-started with the standard configuration results in a "Preset Not Found" error during

Currently, I am in the process of conducting a unit test by referring to the official guide provided. To do so, I have cloned the demonstration repository named vue-test-utils-getting-started. To replicate the issue, follow these steps: After cloning vu ...

A step-by-step guide on incorporating Google Ads Manager Ads units (Banners) into your website with NuxtJs and VueJs

I currently have an Ads unit set up on my website <script type="text/javascript"> google_ad_client = "ca-pub-2158343444694791";/* AD7 */ google_ad_slot = "AD7"; google_ad_width = 300; google_ad_height = 250; </script ...

Creating a custom pipe that converts seconds to hours and minutes retrieved from an API can be achieved by implementing a transformation function

Can someone please provide guidance on creating a custom pipe in Angular 8 that converts seconds to hours and minutes? Thank you. <div class="col-2" *ngFor="let movie of moviesList"> <div class="movie"> {{ movie.attributes.title }} ...

Exploring date comparisons in TypeScript and Angular 4

I'm currently working on a comparison of dates in typescript/angular 4. In my scenario, I've stored the system date in a variable called 'today' and the database date in a variable named 'dateToBeCheckOut'. My goal was to filt ...

Angular 11 is throwing an error stating that the type 'Observable<Object>' is lacking certain properties as required by its type definition

My code is producing the following error: TS2739 (TS) Type 'Observable<Object>' is missing the following properties from type 'WeatherForecast': ID, date, temperatureC, temperatureF, summary I'm puzzled as to why this error ...

Modify the image inside a div when hovering

How can I create a product card that displays thumbnails of images when hovered over, and changes the main image to the thumbnail image? My current challenge is getting this functionality to work individually for each card on an e-commerce site. Currently, ...