iarna / iarna-toml

Better TOML parsing and stringifying all in that familiar JSON interface.
ISC License
320 stars 43 forks source link

dotted keys are quoted #58

Open jrouly opened 1 day ago

jrouly commented 1 day ago

I'm not entirely sure why this behavior is as such:

> var stringify = require('@iarna/toml/stringify')
undefined
> stringify({ 'a.pple': "apple" })
'"a.pple" = "apple"\n'
> stringify({ 'a': "apple" })
'a = "apple"\n'

but the quoted key "a.pple" breaks in several different downstream tools I'm using. the current issue is ruff parsing ruff.toml and complaining that ["lint.per-file-ignores"] is invalid, where [lint.per-file-ignores] was expected.

jrouly commented 1 day ago

I'd point out that the underlying Javascript JSON.stringify quotes all keys, not just dotted keys. So I'm not sure if this is due to the underlying functionality or if this package is doing its own quotation.

> JSON.stringify({'a.pple': 'apple'})
'{"a.pple":"apple"}'
> JSON.stringify({'a': 'apple'})
'{"a":"apple"}'
jrouly commented 1 day ago

Looks like it's these lines. Specifically, "a.pple" doesn't match the string regex so it gets handed off to stringifyBasicString which intentionally adds quotes.

That's frustrating. This doesn't seem like it's going to be configurable behavior downstream.

function stringifyKey (key) {
  const keyStr = String(key)
  if (/^[-A-Za-z0-9_]+$/.test(keyStr)) {
    return keyStr
  } else {
    return stringifyBasicString(keyStr)
  }
}

function stringifyBasicString (str) {
  return '"' + escapeString(str).replace(/"/g, '\\"') + '"'
}