Converting a string with key/value pairs into a JSON object: Step-by-step guide

Is there a way to transform a string of key=value pairs into a JSON object?

Here is an example input:

test = one
testTwo = two

The expected output as a JSON object should be:

{"test": "one", "testTwo": "two"}

Answer №1

How can we check if the variable input is a string? One way is to split it by the newline character (\n) to create an array of key/value pairs. Then, you can further split each pair by the equals sign (=) to separate the key and value into another array.

var input = `test = one
testTwo = two
testThree = three
testFour = four`;

var output = input.split('\n').reduce(function(o,pair) {
   pair = pair.split(' = ');
   return o[pair[0]] = pair[1], o;
}, {});

console.log(output);

Answer №2

The most secure method is to utilize JSON.parse(string)

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

incorporating new content into a jQuery list widget

i am currently exploring this demo for niceforms: http://www.emblematiq.com/lab/niceforms/demo/v20/niceforms.html i want to understand how i can integrate a datasource with the existing list on this page: <select size="4" name="languages[]" id="langu ...

Accessing a JSON value within the AngularJS controller for the purpose of making edits

Seeking assistance here, as I work with a JSON file to generate a timeline using AngularJS. While I've successfully utilized the ng-repeat loop in HTML binding to display dates, I now need to modify the date format – specifically, changing "2013-01- ...

What is the best way to determine if a variable is an object array or not?

I need to determine whether a variable is an Object array or not. Consider the following example data: var myColumnDefs = [ {key:"label", sortable:true, resizeable:true}, {key:"notes", sortable:true,resizeab ...

What could be causing the console to display undefined?

Can anyone help me with an issue I'm having while making an AJAX call using fetch and promises? I have successfully displayed the temperatures, but for some reason, the location is showing up as undefined. Here is the code snippet: function getWeat ...

"The debate over using 'stringly typed' functions, having numerous redundant functions, or utilizing TypeScript's string enums continues to divide the programming

I have a specific object structure that contains information about countries and their respective cities: const geo = { europe: { germany: ['berlin', 'hamburg', 'cologne'], france: ['toulouse', ' ...

Chrome is having trouble loading basic JavaScript

Here's the JavaScript code I have placed inside the head tag of my HTML: <script type="text/javascript"> function over1() { var img1 = document.getElementById("1").src; document.getElementById("big").src = img1; } function out() { ...

How can permissions for video and audio be configured in Next.js?

When the button is clicked, I want to set permissions. This is how I'd like the scenario to play out: first, the method works initially and allows permission when the button is pressed. Here is my code: <button onClick={requestPermission} classN ...

Incorporate the "series:" tag into Highcharts directly from the JSON data retrieved from the server

I am facing an issue with creating a Highcharts chart. I am unable to populate the "series" field with the JSON response returned from the server using PHP. The chart is not being rendered and shows a white background instead. Below, you can find the PHP c ...

Clearing the text within textboxes when they are hidden

I am working on an HTML program that includes a checklist. I have it set up so that when I click on an item in the checklist, a text box is displayed, and when I uncheck the item, the text box hides. How can I make it so that when I uncheck an item, the co ...

Challenges with JavaScript Regular Expressions

Looking to extract a specific Number enclosed within square brackets, like so: Identify the 0 within actionFields[actionFields][0][data[Report][action]] I've been working on this but keep getting a null result. var match, matchRegEx = /^\(?&bs ...

What is the best way to run a callback once several Ajax requests have finished?

I am facing a challenge with executing a callback function after multiple jQuery Ajax requests have been completed. The issue arises when these Ajax requests call another function, resulting in the functions being undefined. I suspect that the root of ...

Step-by-Step Guide to Cutting a Cube with Three.js

I am facing a unique challenge that I haven't seen discussed before. From my limited knowledge of how 3D objects are rendered using webgl and three.js, it appears that I am struggling to create a geometric shape similar to a parallelepiped that does ...

How can one stop users from navigating away from a webpage using the back button on their browser?

1) I'm currently exploring options to display a confirm pop-up when a user tries to leave a page using the browser's back button. It seems that the unload event does not trigger in this scenario. My application is built using angular2. I have att ...

Convert an array to a string using a JavaScript function

I am encountering an issue with the code below: Every time I pass the Array to "track," I encounter an error. It seems like there might be a mismatch between passing an object and a string as input, but I am uncertain and unable to verify. for (var i = 0; ...

Unlocking the power of site JavaScript functions with webdriverIO

Struggling with accessing code from the browser console? Specifically, encountering issues with a Tawk_Api function Tawk_API.hideWidget();. Attempts to utilize browser execute and call have resulted in an error message stating that Tawk.Api is not defined. ...

Establishing a standard flatiron-director route (within the element) using the polymer core-pages component

This particular query is closely linked with issues surrounding the usage of flatiron-director/core-pages SPA in conjunction with route-specific JavaScript functions and default routes. While the solution proposed may be effective, my limited expertise in ...

What are some ways I can optimize this code for faster performance using async/await and promises?

In my Node.js project, I have been tasked with optimizing the code that currently makes 60 HTTP requests using libraries. The process of making these requests and saving them to a file takes around 30 seconds. It has been suggested that it is possible to ...

[FileSaver - Blob] The data parameter must be a valid blob object

My current issue involves utilizing angular-file-saver to export a table into an xlsx file. The table is contained within a div specified by $document[0].getElementById('exportable').innerHTML. To achieve this, I am creating a Blob object which ...

What is the reason why certain variables in req.body can be read by Express.js while others cannot?

Currently, I am not utilizing body-parser and it is clear that I need to incorporate it. My query pertains to the inconsistency in how my variables are being accessed through req.body without body-parser. Some of the variables display undefined values whil ...

Determining in Angular whether a component tag includes a specific attribute

My usage of the app-somecomponent looks like this: <app-somecomponent required></app-somecomponent> I am trying to determine if the app-somecomponent element has the required attribute set in the app-somecomponent.component.ts file without sp ...