Simple JSON Encode/Decode in Pure Lua
More Lua code

I've coded up some simple JSON encode/decode routines in pure Lua and thought I'd share them in case anyone else would find them useful. I use them in Adobe Lightroom, but they're pure Lua 5, so can be used anywhere Lua is.

Creative Commons License
JSON Encode/Decode in Pure LUA by Jeffrey Friedl is licensed under a Creative Commons Attribution 3.0 Unported License.
Download JSON.lua
Version 20161109.21 (version 21: Nov 9, 2016)

Full docs and changelog are in the code itself, but basic use is:

JSON = (loadfile "JSON.lua")() -- one-time load of the routines

local lua_value = JSON:decode(raw_json_text) -- decode example

local raw_json_text    = JSON:encode(lua_table_or_value)        -- encode example
local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version


(You might also be interested in this comparison of Lua JSON packages.)

All 28 comments so far, oldest first...

When I add this line to a plugin I am writing I get an error from Lightroom

MyPluginApi:28 cannot open JSON:lua: No such file or directory

The thing that makes no sense to me is that the JSON.lua file is located in the same directory as MyPluginApi.lua

Do you have an example plugin that might show the usage of this JSON library working?


It looks as if you have a colon before ‘lua’ rather than a dot. —Jeffrey

— comment by Robert on July 25th, 2011 at 6:30am JST (5 years, 8 months ago) comment permalink

Hi, I’ve recently noticed your module and included it in my comparison of JSON modules on the Lua wiki. Your module is one of the better pure-Lua JSON implementations and I guess I wouldn’t have needed to write my own if I had found yours earlier. I hope you don’t mind the inclusion in the list.

Thanks for the link, and for the tests. I’ve pushed a new version that addresses some of the problems you found in your tests. Thanks! —Jeffrey

— comment by David Kolf on July 30th, 2011 at 7:30am JST (5 years, 8 months ago) comment permalink


thanks for this. I’ve just checked out the file, but I didn’t find any info regarding the license type, just your copyright notice.

From a legal perspective, if the code comes without a license everyone can have a look but no one can use it, for any type of project. So are there any strings attached?



Feel free to use it as you like. —Jeffrey

— comment by Michael on October 1st, 2011 at 7:51am JST (5 years, 6 months ago) comment permalink

I really like to use your module, but I can’t unless there is a license that clearly grants me permission to use it. For example MIT, like lua license itself, or BSD 2-clause.


I made it and I said you can use it. That should be enough. —Jeffrey

— comment by MaikB on October 21st, 2011 at 3:08am JST (5 years, 5 months ago) comment permalink

Err… something seems to be up with the comments in the file:
Lines 14 and 123 have -- JSON = (loadfile "JSON.lua")() -- one-time load of the routines
While lines 24 and 111 have -- JSON = (loadfile "JSON:lua")() -- one-time load of the routines

That JSON.lua / JSON:lua is a bit inconsistent… Is that intentional? (Considering that Lightroom just gave me the error “attempt to call a nil value” when I tried loading JSON:lua, I doubt it…)

Also, THANK YOU for publishing this. It’s making my first foray into Lightroom plugin development (and Lua) so much easier!

(While I’m at it, any pointers on using relative paths in loadfile(), or, alternatively, finding out with directory is Lightroom’s working directory so I can build a relative path from that? Doing loadfile(JSON.lua) falls over with File not found, but putting the absolute path in works fine, but… won’t work for anyone but me, which is not an optimal solution.

And Lightroom’s file access is too fast to show up in Process Explorer, so I can’t get anything from there.)

Oops, thanks, I thought I fixed that once, but apparently not in my master source, so it reared its ugly head again. It should be dot-“lua” in all situations, so I’ve fixed it (again), thanks. As for the path stuff, try loadfile(LrPathUtils.child(_PLUGIN.path, “JSON.lua”)) or the like. —Jeffrey

— comment by Kyle (Singapore) on December 23rd, 2011 at 12:41pm JST (5 years, 3 months ago) comment permalink

Hi, i want to use this library in my project. Could you please add some example how to use it. I have a json string. First i want to extract it to an array then to an object. and then get a string with the key “text”

I’m new to lua, some exapmles would be neat

— comment by joer on July 5th, 2012 at 11:03pm JST (4 years, 9 months ago) comment permalink

I just included your JSON.lua file in my project: I hope it’s fine.

Sure, it’s fine, you’re not the only one these days. I realize, though, that there was no link back to this page, so it’s harder for folks to check for updates, so I’ve added a link in the code directly back to this page. —Jeffrey

— comment by etu on January 20th, 2013 at 2:48am JST (4 years, 2 months ago) comment permalink


It says “Version 20130120.6 (version 6, Jan 20, 2013)”, but in the changelog at the bottom of the linked file, it stops at version 5. Is it really the 6th version ? And if yes, what’s different from version 5 ?

Thank you.

The only difference is in a comment, so there’s no real difference. Not sure why it didn’t update before, but it’s updated now; thanks for the heads up. —Jeffrey

— comment by g012 on May 13th, 2013 at 9:44pm JST (3 years, 11 months ago) comment permalink


Thanks – great module.

Would you mind putting the ‘Feel free to use this any way you like” comment in the code (or just say you are placing in the public domain) rather than just in the blog. That would make your intentions clear to anyone auditing code later, which sadly gets done.


I’ve updated the code and the web page to reflect a Creative Commons “CC-BY” license, which is what I really should have done from the beginning. —Jeffrey

— comment by Alex Bligh on October 4th, 2013 at 3:06am JST (3 years, 6 months ago) comment permalink

Hi Jeffrey,

I’m new to lua (since yesterday) and I was playing around with your nice module.
I’m runnin into a few issues / unclarities though and hope to get them clarified.

The pretty_encode does not generate the same output as the encode when it comes to ‘arrays’.
Consider the following:

local Test = {1, 2, 3, [5]=5} -- would be a table with Test[4] = nil
-- encode output: [1, 2, 3, null, 5]
-- pretty_encode output: [1, 2, 3]

Secondly, in the comments you put:

-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.

Which would indicate that

Test = { [1] = "a", [2] = "b", ["3"] = "c" }

results in a JSON object (ther is ‘any strings’), instead i get a ‘mixed keys’ error.

Hope you can help me out,

Mattie (Netherlands)

Thanks for the heads up on these… I’ve pushed a new version that addresses both issues. —Jeffrey

— comment by Mattie on October 31st, 2013 at 5:25am JST (3 years, 5 months ago) comment permalink

Hey there from Spain!

I just wanted to thank you for releasing this, it literally saved my life, as I am using Lua in a closed environment for a project, and the functions they provided me to work with JSON were pretty lame.

And I must also say thanks for your pure lua sha1 implementation! ; )


— comment by Pablo PHG on November 28th, 2013 at 10:32pm JST (3 years, 4 months ago) comment permalink

Hi Jeffrey

Thanks for your JSON module. I stumbled across the following issue (using version 20131118.9):
JSON:decode(“[1,null,3]”) silently skips the “null” value and result in a table with two values only: {1, 3}.

This seems to be because of the problem described here:

The following one-line change would allow an application to define a nilPlaceholder in your module:

— JSON.lua.old 2013-11-18 13:07:36.000000000 +0100
+++ JSON.lua 2013-12-20 14:47:28.636625937 +0100
@@ -506,7 +506,7 @@
return false, start + 5

elseif text:find(‘^null’, start) then
– return nil, start + 4
+ return JSON.nilPlaceholder, start + 4

self:onDecodeError(“can’t parse JSON”, text, start, etc)

For example:

local NIL = {}
JSON.nilPlaceholder = NIL

The calling application could then compare the received values with NIL. If nilPlaceholder is not defined, it is simply “nil”.

Thanks and keep up the good work!

Oliver (Switzerland)

Yikes, I just (April 2014) noticed this comment sitting in moderation. Sorry. It turns out that I did notice a comment of someone else reporting the bug many months later, and have just (April 2014) pushed a fix. The fix doesn’t require any placeholder thing… it just works. Sorry for the delay(!) —Jeffrey

— comment by Oliver Hitz on December 20th, 2013 at 10:51pm JST (3 years, 3 months ago) comment permalink

Hello Jeffrey,

Thank you very much for making your code available.
When trying to decode a malformed JSON:

{"sleepCycle": 15,a"enabled": 1}

your code gets to line 550:

      -- should never get here... JSON parse errors should have been caught earlier
      assert(false, value)

and fails. Although it says it should not get there, it’s there.
Anyway I think the right code should be:

      -- should never get here... JSON parse errors should have been caught earlier
      -- assert(false, value)
	   if self.assert then
		  self.assert(false, message)
		  assert(false, message)

To be able to catch the exception. Do you agree?
Best regards.

Good catch… the “should never get here” comment is true only if the user’s JSON.assert actually breaks out of the pcall, as it does when I use it in Adobe Lightroom, so it’s not an appropriate comment for the general package, so I’ve updated it, and the code as you suggest (with s/message/value/). Thanks for the heads up. —Jeffrey

— comment by blue on January 16th, 2014 at 6:24am JST (3 years, 2 months ago) comment permalink

Hi Jeffrey,

When decoding [“1″,null,null,null,null,null,”marathon”], it returns an array of two elements ({1,marathon}).
It may be a normal behavior, but it would be helpful if it returns an array of 7 elements with nil values (something like {1,nil,nil,nil,nil,nil,marathon}).

Thank you for your work, it saved me a lot of time, here in Canada 🙂

Good catch, thanks. I’ve pushed a fix. —Jeffrey

— comment by haddock on April 18th, 2014 at 1:53am JST (2 years, 11 months ago) comment permalink

Nice job: thank you!

— comment by Rick77 on May 19th, 2015 at 6:40pm JST (1 year, 10 months ago) comment permalink

HI Jeffrey,
When decoding a 900K json file, json lib will cost 14M+ memory. I review json.lua, and find use many stringcat .. operation at grok_string function.
so I change VALUE = VALUE .. c to tmp_stream:insert(c). diff code is here: using table.concat would be faster and reduce string memory allocation.

you can review code : 😉

Unfortunately, whatever this “insert” function is, it’s not available in the version of Lua that I use. —Jeffrey

— comment by zixun on June 12th, 2015 at 12:55pm JST (1 year, 10 months ago) comment permalink

Forked this repo for LuaRocks. Do you have GitHub account for this?

No, sorry, no GitHub. —Jeffrey

— comment by jiyinyiyong on June 26th, 2015 at 11:02pm JST (1 year, 9 months ago) comment permalink

Hi Jeffrey,
thanks for the code. This is exactly what I was looking for. Works like a charme – in a Lightroom plugin!
So far, only simple JSON responses are decoded (did this with a regexp before), but it will probably become more important when using more sophisticated WebAPIs of the Synology PhotoStation.

Greetings from Berlin,


— comment by Martin on September 19th, 2015 at 7:35am JST (1 year, 6 months ago) comment permalink

Hi Jeffrey,
Thanks a lot for this code ! Excellent work ! We are using this serilizer together with Zabbix JSON-RPC API in a large distributed monitoring network. This code provided us with an excellent jumpstart at first when we made a prototype of the gateway from Zabbix to internal ESB. After a while we have decided not to touch anything as it works perfectly and performance is sufficient for this project.

Thanks a lot again,
Greetings from Kazakhstan,

— comment by Paul on October 7th, 2015 at 7:18pm JST (1 year, 6 months ago) comment permalink


I am new to Lightroom plugin development: I can’t find the correct syntax to load your JSON.lua file. I have put the JSON.lua file in the plugin folder. I have tried some code found on this page:
JSON = (loadfile “JSON.lua”)()
JSON = assert(loadfile “JSON.lua”)()
JSON = loadfile(LrPathUtils.child(_PLUGIN.path, “JSON.lua”))
without success.
Could you please give the correct syntax to use (Lightroom 6 Plugin SDK ).
Thanks a lot

In Lightroom you can use JSON = require "JSON.lua", but note that Lightroom won’t recognize any file added to a plugin folder after it starts, so after having added the JSON.lua file, you have to restart Lightroom before anything will work. —Jeffrey

— comment by Thierry on October 26th, 2015 at 10:21pm JST (1 year, 5 months ago) comment permalink

During encode(), numbers larger than 1e14 were being changed to scientific notation.

Here is some lua code to show how tostring() handles large numbers
> x=100000000000001
> print(tonumber(x));
> print(string.format(“%.0f”,x))

I changes the encoding to use the “%.0f” format -> works great

Here is the GIT DIFF
@@ -837,7 +837,10 @@ function encode_value(self, value, parents, etc, options, indent)

return “-1e+9999”
– return tostring(value)
+ return string.format(“%.0f”, value);

Ah, good catch, but unfortunately it’s not quite that simple. Try with your x value set to 10000000000054321, 10000000000054322, and 10000000000054321+1 and you’ll see (if your system is the same as mine) that at some point the string.format() version is wrong, due, I’m sure, to precision being lost in encoding big numbers in too-small a number of bits. I’d rather see that loss of precision represented, instead of a wrong number presented precisely.

There’s a range of decimals for which string.format() is indeed better, as your example shows; if I can determine for sure such cases, I’ll incorporate a change for them. I just tried the obvious way and it was lacking, but I’ll dig further.

Of course, we still need to make sure that a number like 3.14159 is output correctly.—Jeffrey

— comment by Russell Sullivan on April 22nd, 2016 at 9:29am JST (11 months, 7 days ago) comment permalink

I am not able to do loadfile with LUA called from HAProxy config

JSON = (loadfile “JSON.lua”)()

The program exists for loadfile call.
The caller lua and JSON.lua are placed in same folder.

Is there specific configuration needed for HAProxy?

— comment by Deepak Agarwal on May 17th, 2016 at 2:19am JST (10 months, 12 days ago) comment permalink

Any thoughts or ways around having decode properly handling nil values from a table?

For instance:
“somevalue”: null

will create a empty output since lua doesn’t support nil values as a key in a table element.

I’ve locally (and horribly) solved this by patching if nil to return a function that returns nil — but looking at the table I have to account for that too — then on the encode I just say if it’s a function then it is nil — good enough for me, but not for a general stance.
local function grok_object(self, text, start, etc)
VALUE[key] = new_val or function() return nil end

function encode_value(self, value, parents, etc, options, indent)
if type(value) == ‘function’ then value = nil end
if value == nil then
return ‘null’

Other than this small hiccup, I really love how the rest works… Efficient and stable!

As of version 20160526.15 I’ve added a “null” field to the encoding-options table. If your Lua table has a string value with the same value as the “null” option, it gets encoded into JSON as a raw null. Using null="\0" might be appropriate, for example. —Jeffrey

— comment by Adam B on May 25th, 2016 at 5:50pm JST (10 months, 4 days ago) comment permalink

Thanks a lot for this! I’m using to create and load save files for a game I’m working on, and it works great. One small suggestion would be to ignore functions while parsing, rather than throwing an error. This is only my opinion, of course.

Anyway, I am quite happy with this library. It was the first result when I searched for “lua json parser.”

As an aside, what do you use this library for in Lightroom?

Since you asked where I’m from: Portland, Oregon.

I’m not sure what you mean by “ignore functions while parsing”; JSON has no concept of “functions”. I use this in my Lightroom plugins to handle responses from a variety of photo-hosting-site’s APIs. —Jeffrey

— comment by MarkSill on May 29th, 2016 at 3:58pm JST (10 months ago) comment permalink

I have found a bug when decoding an empty object, it is interpreted as an empty array, at least that is what shows on encode().
look at the field: ‘attributes’, it is an object in the string and then an array on decode()

> JSON = (loadfile “./JSON.lua”)();– one-time load routines
> x='{“id”:”UserInfo_BILL”,”actions”:[],”attributes”:{}}’
> y=JSON:decode(x)
> print(JSON:encode(y));

As mentioned in the docs, it’s handled correctly if you “JSON.strictTypes = true“. It’s not the default because supporting it requires adding metatables to the data, which can break some systems into which Lua is embedded. —Jeffrey

— comment by Russell Sullivan on June 4th, 2016 at 5:42am JST (9 months, 25 days ago) comment permalink

Thank you for making this module!

I think I have spotted an unintended global. On line 516, you have:
> local isNumber = {
> __index = isNumber,
> — <snip>
> }
However, when __index = isNumber on line 517 is parsed, nothing has been assigned to the local isNumber variable on line 516 yet, so at that point isNumber is treated as an uninitialised global, and __index is assigned a value of nil. (At least, this is how it works in Lua 5.1.)

I haven’t followed all the paths through the code to see if this causes any problems, but I guess that this isn’t what was intended.

Holy cow, you’re right. What a nubie mistake on my part. Good catch, thanks. Fixed. —Jeffrey

— comment by Jack Taylor on September 16th, 2016 at 3:22pm JST (6 months, 13 days ago) comment permalink

This is an awesome module, thanks a lot!

Wanted to know, sadly in the project I’m testing, ‘the order’ of some keys in the json file needs to be preserved, my question is, is it possible when reading a json to keep the original order in which they were read?
decoding/encoding the same file changes the order of key-value pairs.

It’s not currently possible, sorry. Lua tables have no order for non-numeric keys, so to preserve the order you’d have to use metatables somehow, which just opens up a can of worms for handling that metadata (e.g. what to do when new keys are added in Lua). —Jeffrey

— comment by Alejandro on September 29th, 2016 at 7:44am JST (6 months ago) comment permalink

Hello again, and thank you for the updates to the module dealing with trailing garbage. I’ve spotted another nil global bug in the new code, so I thought I would let you know.

On line 1065, you have this variable declaration:

> local error_message

This declaration is in the scope of the if block starting at line 1060.

> if next_i ~= #text + 1 then

The problem is that on line 1070 you try and use error_message:

> return value, error_message

But at that point we have left the scope of the if block, so error_message is a nil global.

If you could update the code to fix this, it would be much appreciated.

Oops, sorry, I fixed this earlier in the month but goofed up pushing out the fixed version here. It (version 20161109.21) is here now. —Jeffrey

— comment by Jack Taylor on November 24th, 2016 at 12:29pm JST (4 months, 5 days ago) comment permalink
Leave a comment...

All comments are invisible to others until Jeffrey approves them.

Please mention what part of the world you're writing from, if you don't mind. It's always interesting to see where people are visiting from.

You can use basic HTML; be sure to close tags properly.

Subscribe without commenting