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.