简体   繁体   中英

Convert a multiline key:value string to JSON

I am trying to convert a multiline key:value string to JSON. Reason is I need to create HTTP headers out of it for an ajax request sample data

content-type:text host:myhost.com

I want it to become

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

I tried playing around and checked some documents and this is the best I got from Github

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 works fine but the format is incorrect. I got this instead:

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

the double quotes are missing from the keys. I tried logging the jsonString before parsing it and the format is good. but once it is parsed using JSON.parse, the doublequote went missing

I hope someone can enlighten me what else I forgot to add.

your function strToJSON outputs a javascript object. you'd need to convert it into a JSON string if you want JSON:

JSON.stringify(strToJSON("content-type:text host:myhost.com"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM