Transforming JavaScript objects into URL string formats (JSON)

I am faced with a JSON object that has the following structure:

{
    "version" : "22",
    "who: : "234234234234"
}

My goal is to convert this into a string format that can be easily sent as a raw http body request.

Essentially, I need it to be formatted as:

version=22&who=234324324324

The challenge lies in making sure this conversion works for an infinite number of parameters. Currently, I have come up with the following method:

app.jsonToRaw = function(object) {
    var str = "";
    for (var index in object) str = str + index + "=" + object[index] + "&";
    return str.substring(0, str.length - 1);
};

However, I believe there must be a more efficient way to achieve this using native JavaScript?

Thank you.

Answer №1

Latest update as of 2018

var obj = {
    "version" : "22",
    "who" : "234234234234"
};

const queryString = Object.entries(obj).map(([key, value]) => {
    return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
}).join('&');

console.log(queryString); // "version=22&who=234234234234"

Original post

Your solution is pretty good. One that looks better could be:

var obj = {
    "version" : "22",
    "who" : "234234234234"
};

var str = Object.keys(obj).map(function(key){ 
  return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]); 
}).join('&');

console.log(str); //"version=22&who=234234234234"

+1 @Pointy for encodeURIComponent

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

Troubleshooting the issue with nodejs fs createWriteStream and file path prefixes

My goal is to call an API, iterate through an array of images, assign unique names to each image in the array, and then save them to a local directory. By simplifying the code, I can achieve this by writing them to the root folder. The sub folder was alrea ...

I am receiving JSON data on my Android device, but for some reason, it is not parsing correctly. Can anyone help me diagnose the

Here is the JSON format as mentioned in the title: http://prntscr.com/elb4fz. I am uncertain about the parse method functioning correctly since I believe that SearchResults is an array and each result will be displayed as an object. The networkutils code ...

Tabulator - Using AJAX to retrieve a JSON document

I am currently working on importing a json file from an Azure blob container using Azure Data Factory. Despite closely following the documentation and researching various resources on Stack Overflow, I am facing challenges with making the ajax request fun ...

JavaScript interface for touch events

Hi there! I'm wondering if there's a touch phone equivalent of the js onmousemove function (jquery mousemove). It seems like jQuery mobile doesn't have it, and I'm still fairly new to all of this mobile development. /tn ...

Is there a way to apply the active class without relying on an anchor element?

After creating a one-page website, I utilized JavaScript to prevent the hash from appearing in the URL. Here is the HTML code: <ul class="click crsl"> <li><a class="page1 dot active"></a></li> <li><a class=" ...

The activation slot in Vue JS Vuetify menu is not properly binding to the template and instead is defaulting to the "default" slot

I’m having trouble getting the Vuetify v-menu example code to function properly within my PWA app. Strangely, it works perfectly fine in a Fiddle (for example: https://jsfiddle.net/tjw13yz4/27/) The issue I'm facing is that the activator slot conte ...

Is the user input malfunctioning?

I'm experiencing an issue in my Node.js program where it seems to be skipping the first user input function and directly executing the second one. I've been troubleshooting this, but so far, I haven't been able to find a solution. Any insigh ...

"The authentication cookie fields are not defined when trying to get the authentication in the Express framework

After setting up my React client on port 3000 and Express on port 5000, I encountered an issue. When logging in, the cookie fields are set without any problems. However, when trying to retrieve the isauth value, it shows as undefined. //login log message ...

Remove the list by conducting a comparison analysis

<html> <head> <title> Manipulating List Items Using JavaScript </title> <script type="text/javascript"> function appendNewNode(){ if(!document.getElementById) return; var newlisttext = document.changeform.newlist.val ...

Error: identifier token was not expected

I'm struggling to make an ajax request using DataTable.js, but I can't seem to connect the dots. let php_data = '<?php echo $_path."|".json_encode($LNG). "|".json_encode($array_uzers)."|".$month ."|".$year."|".$membre."|".$user ."|".$deb ...

Navigating through pages in React using Pagination Animations

Attempting to style an active button with a small transition when it receives that attribute has been a challenge. The same issue occurs with the paragraph rendered from the data file. function Pagination() { const [selected, setSelected] = useState(0) ...

Learn how to retrieve all offspring of a JSON object in C# by utilizing NewtonSoftJson

Welcome, User! Here is my JSON: I am trying to extract all usernames from the data list using C# and Newtonsoft.Json. I'm hopeful that someone can provide me with some guidance. I attempted the following approach but encountered issues: "kind":"Us ...

Error: The program is encountering an issue because it is trying to scan a file that is not a directory in the "./src/functions/" path. This error message appears when the program encounters a "

node:internal/fs/utils:351 throw err; ^ Error: ENOTDIR: not a directory, scandir './src/functions/.DS_Store' at Object.readdirSync (node:fs:1532:3) at Object.<anonymous> (/Users/roopa/Desktop/projects/LLbot/src/bot.js:43:6 ...

What steps can I take to give priority to a particular ajax call?

Every 10 seconds, two ajax based methods are executed. However, when I submit the form for processing, it waits for the previous ajax calls to complete before processing. I want to prioritize the form submission. Below is the script that I am using: func ...

Developing a custom function within an iterative loop

Can someone assist me with a coding problem? I have these 4 functions that I want to convert into a loop: function Incr1(){ document.forms[0].NavigationButton.value='Next'; document.PledgeForm.FUDF9.value='Y1'; document.fo ...

Secure animated boxes with jQuery for showing and hiding - indestructible!

My goal is to create a dynamic effect where the content box on a page changes upon hover. Initially, the box displays a heading (or image, or other element). Upon hovering over the box, the original content fades out while new content fades in and the box ...

When it comes to implementing Ajax and Json in Ruby on Rails, the action url can sometimes be a

Apologies for any language issues. I am wondering about using "get" in JQuery when the url is an action reachable from the browser. In my js file: $.get('/user').success(function(data) { availableTags = data;} ); This is my controller: class U ...

Trigger the input with a delay function, pause if the input value is modified

I am in the process of creating an angular directive that will run a function when the input value changes. I want to implement a 300ms delay before running this function, but if the value changes again within the 300ms timeframe, I need to reset the delay ...

Storing data in HTML5 localStorage using XML or JSON format

A sample of an XML file is provided below: <itemnumbers> <item> <itemno>123</itemno> <desc>Desc about 123</desc> </item> <item> <itemno>456</itemno> <desc/> </item> ... </itemnu ...

What is the importance of utilizing state changes for React developers when working with CSS Pseudo classes?

Could someone please clarify why, in React, state changes are necessary for CSS Pseudo classes such as hover, focus, active, etc? Why didn't the developers of React keep it simple like we do in regular CSS? ...