javascriptjsonstringparsingkey-value

How to parse a string of key/value pairs in JavasScript, with pairs separated by commas?


I would like to be able to parse a sting such as

'a=1, b="two", c=[1,"two", {"a":1}]'

Into a JSON string or Javascript object such as

{ 
  "a": 1, 
  "b": "two", 
  "c": [1, "two", {"a":1}] 
}

This question is similar to Parse string having key=value pairs as JSON and Javascript Parsing Key Value String to JSON, but having the KV pairs separated by commas is challenging because the values themselves can have commas.

Suggestions? Existing packages?


Solution

  • Dec 2024

    some new tools have come around ;)

    This works perfectly with my command line tool I am using to parse an unlimited amount of env variables passed to the bash script.

    Example String input:

    const str = options.env as string // TEST=app-test,ONE=app,IT=onemore
    
    const env = str.split(",").reduce((acc: { [key: string]: string }, curr) => {
      const [key, value] = curr.split("=")
      acc[key.trim()] = value.trim().replace(/['"]/g, "")
      return acc
    }, {})
    
    console.log(env)
    

    Example output:

    { TEST: 'app-test', ONE: 'app', IT: 'onemore' }