lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sat, Sep 11, 2010 at 5:07 PM, Alexander Gladysh <agladysh@gmail.com> wrote:
> On Sun, Sep 12, 2010 at 01:23, Thomas Harning Jr. <harningt@gmail.com> wrote:>
>> On 9/11/10, Alexander Gladysh <agladysh@gmail.com> wrote:
>
>>> While we're on it: I have a special case (not for default json2lua
>>> mode) where I need luajson to convert JSON string keys that are
>>> numbers (like "1" or "123.456", but not "123a") to numbers in Lua.
>
>>> Example:
>
>>> { "key": "value", "1": "one", "20": "twenty" }
>
>>> Becomes:
>
>>> { ["key"] = "value", [1] = "one", [20] = "twenty" }
>
>>> Is this possible?
>
>> It is possible, it may take a tweak in the handling code to add the capability
>
> Um, thanks. Where should I start digging?
>
> Alexander.
>
>
Alrighty, now that I at least have source access...  If you have
numbers as keys, but without quotes, it will put them in numeric
indices.  If you want to transform all strings that happen to be
numbers, here is a small patch to my current source code that would
have the effect that you desire...

Change (in json/decode/object.lua)
	else
		objectItems = buildItemSequence(lpeg.Cg(objectItem), ignored)
		objectItems = lpeg.Cf(lpeg.Ct(0) * objectItems, rawset)
	end
To:
	else
		objectItems = buildItemSequence(lpeg.Cg(objectItem), ignored)
		local function setObjectKey(t, key, value)
			key = tonumber(key) or key
			return rawset(t, key, value)
		end
		objectItems = lpeg.Cf(lpeg.Ct(0) * objectItems, setObjectKey)
	end

And be sure to add "local tonumber = tonumber" at the top of the file
(below tostring setting would make sense)


Looks like 'key' handling could use customizability in my library...

-- 
Thomas Harning Jr.