kcwiki/lua-json

Doesn't return brackets on all keys

Closed this issue · 5 comments

Hello, I'm trying out lua-json and running into an issue when converting json to lua. It seems to add brackets to some keys.

Here are some results I'm seeing-

DB = {
    _currentProfile = {
      ["test1"] = "Default",
      ["test2"] = "test123",
      ["test3"] = "Default",
      ["test4"] = "Default",
    },

When I would expect-

DB = {
   ["_currentProfile"] = {
      ["test1"] = "Default",
      ["test2"] = "test123",
      ["test3"] = "Default",
      ["test4"] = "Default",
    },

Any ideas?

In table fields ["a"] = b is the same as a = b when a is Name ("any string of letters, digits, and underscores, not beginning with a digit [...]"), so the shorter/prettier variant is used when possible via

const formatLuaKey = (string, singleQuote) => (string.match(/^[a-zA-Z_][a-zA-Z_0-9]*$/) ? string : `[${formatLuaString(string, singleQuote)}]`)

Though then it should be test1/etc. instead of ["test1"]/etc. as well, so that one is not intended. I will take a look later.

Can't reproduce here:

// test.js
const { format } = require('lua-json')

console.log(
  format({
    DB: {
      _currentProfile: {
        test1: 'Default',
        test2: 'test123',
        test3: 'Default',
        test4: 'Default',
      },
    },
  }),
)
-- node test
return {
  DB = {
    _currentProfile = {
      test1 = 'Default',
      test2 = 'test123',
      test3 = 'Default',
      test4 = 'Default',
    },
  },
}

Current test also covers this (all keys are short except those that can't be).

Sounds like it's working how you intended. I'll close this and possibly fork as I have an odd use case.

I plan to add some more options for pretty printing, something like an option to always use brackets can be an option as well.