Transform a key:value string with multiple lines into a JSON format

I need to convert a multiline key:value string into JSON so that I can use it to create HTTP headers for an ajax request. Here is a sample data:

content-type:text
host:myhost.com

I want the output to be:

{"content-type":"text",
"host":"myhost.com" }

I have tried different methods and even looked at some GitHub documents, but the best solution I found is this:

strToJSON = (str) => {
let commaAdded = str.replace(/(?:\r\n|\r|\n)/g, ',').trim().replace(/,+$/g, '')
let items = commaAdded.split(',')
let jsonString = items.map(item => {
  return item.replace(/([^:]+)(:)(.+$)/, (match, p1, p2, p3) => {
    return `"${p1.trim()}": "${p3.trim()}"`
  })
}).join(', ')
try {
  return JSON.parse(`{${jsonString}}`)
} catch (err) {
  console.log(err)
}

This function works correctly, except for one issue. Instead of the desired format, I get:

{content-type:"text",
host:"myhost.com" }

The problem is that the keys are missing double quotes. When I log `jsonString` before parsing it, the format looks correct. However, after parsing with `JSON.parse`, the double quotes disappear.

I am hoping someone can help me figure out what else I need to add or change in my code.

Answer №1

the function strToJSON returns a JavaScript object, but if you require JSON format, you must convert it into a string using:

let jsonString = JSON.stringify(strToJSON("content-type:text host:myhost.com"));
console.log(jsonString);

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

Verify the data type of the BSON field to identify whether it is a $numberDecimal in MongoDB when using Node.js

I have a tricky task at hand where I'm dealing with a mongo aggregate pipeline result that contains Decimal128 values that need to be converted to regular numbers. For example: amount: { $numberDecimal: '200' } <-- unwanted format amount: ...

Include specific javascript files only for smartphones

Recently, I encountered an issue with a JavaScript code that swaps background images on scroll down. To address the problem with debounce, I ended up setting different debounce times for various browsers (I am aware this is not the ideal solution, but it&a ...

Tips for effectively transmitting and managing a JSON object within an ASP.NET MVC controller

I am currently working on a project using ASP.NET MVC 4 and I'm facing an issue with sending a JSON object to a controller that is supposed to accept it. Here is the snippet of javascript and jQuery code I am using: var jsonObject = { "PlantShip ...

The popup image on my main project is not functioning correctly, despite working perfectly in my test project

I am working on creating a pop-up image for my internship project. When the user clicks on an image, I want it to display in a larger size with a background and opacity. However, the code I have implemented so far is not functioning properly. Please ignore ...

Issue with $scope.$watch function inconsistency

In my sign-in form, I am facing an issue with handling errors. The form slides in from the left using a custom directive. However, when I try to slide it out of sight, I need the current error to disappear as well. I have tried using a $watch function to m ...

What is preventing me from "importing" react-dom.js?

Implementing ReactDOM into my Jest tests has been a bit of a challenge. Let's take a look at the code snippet below. const React = require('../src/js/vendor/react/build/react.js'); const ReactDOM = require('../src/js/vendor/react/build ...

Ways to maximize your final export value

My data file, named data.ts, contains a large dataset: export data = [ ... // huge data ] The lib.ts file only utilizes a portion of the data: import { data } from './data.ts'; const fitteredData = data.splice(0,2) // only use some of them ...

Retrieve the name by using a JSON foreach loop

I'm encountering this error message: Parse error: syntax error, unexpected T_DOUBLE_ARROW, expecting T_PAAMAYIM_NEKUDOTAYIM in /var/www/createRecipeIng.php on line 60 This is a new issue for me and I'm unsure how to resolve it. Below is the c ...

Assign a variable within a Vue composition file

I'm diving into the world of composition API in Vue and I'm uncertain if my approach is breaking any established patterns. I have a desire to initialize a variable directly within the composition file: GameLogic.ts export default function () { ...

What is the best way to automatically adjust a panel's width and height based on the user's screen resolution?

My page is connected to a masterpage. Within this page, I have an update panel that contains an ASP.NET panel. The panel includes a gridview displaying data from the database. Currently, I have set a fixed width and height for the panel. However, if the u ...

Tips for preventing double foreach loops in Laravel when dealing with backward relationships

I'm attempting to display variables using the following relationships: First: public function group(){ return $this->belongsTo(Group::class); } Second: public function joinGroups(){ return $this->hasMany(JoinGr ...

Ways to trigger a function when the body is loaded

In this snippet, I am attempting to execute the oauth2_login() function when the body loads, which is intended to log in the user. Currently, I have hardcoded values from the database into the username and password fields. <!DOCTYPE html> <html&g ...

Using Vue.js and axios to manipulate injected HTML content

I am currently working on a project using vue.js and axios to fetch the latest post content from a specific category of a WordPress site using REST API. The post content is always in the form of an ordered list (OL) which will then be displayed as a carous ...

Can you please explain the importance of the enforce parameter within an AngularJS Factory?

As I delved into the intricacies of how angular constructs factories through the module.factory() method, I discovered that internally angular relies on the following method which in turn utilizes a provider. function factory(name, factoryFn, enforce) Th ...

Modify the button's color based on a separate column within the table

Currently, I am implementing Datatables along with X-editable and including some bootstrap buttons within a table. My objective is to change the color of the button in the 'Validated' column to green when the user updates the editable 'Statu ...

Just a single array in a basic JSON file for integration into my Android application

I'm dealing with a JSON file that contains a single unnamed array, like this: ["Cream","Cheese","Milk","Powder Milk","Blue Cheese","Gouda Cheese"] How can I extract this array and store it in an array or ArrayList in my Android Studio project? An ...

The $firebaseObject variable is not defined

My AngularJs + AngularFire setup includes email/password authentication and a node called "users" to list authenticated users. Here is a snapshot: https://i.sstatic.net/eBz3G.png Within my authentication service, I have an AngularJs factory: .factory(&ap ...

Deciphering JSON responses from the Bit2Check.com API

I am currently utilizing the Bit2Check.com API to verify emails associated with PayPal accounts. However, when I provide an email address to the API, it returns the following response: {"Paypal":"Linked"} My goal is to extract only the "Linked" part from ...

Activate and deactivate form fields on Safari

I have been working on a script to enable and disable a field using Javascript. It functions correctly in Internet Explorer, but I am encountering issues with Safari. FIELD If "Yes" is selected, the free text field below should be enabled; otherwise, it s ...

Example of Utilizing Google Places API

The Issue I've been struggling to make this google maps API example function correctly. Even after directly copying the code from Google's website, the example fails to display properly. For instance, the map doesn't show up, the search bar ...